问题
How do you pass an array to the firebase firestore arrayUnion() function?
I am getting this error when I try to pass an array.
Error
Error: 3 INVALID_ARGUMENT: Cannot convert an array value in an array value.
Example
let myArray = ["1", "2", "3"];
docRef.update({
test: firebase.firestore.FieldValue.arrayUnion(myArray)
});
回答1:
I eventually found the answer of using Function.prototype.apply() in another stack overflow answer.
Example For Function.prototype.apply()
let myArray = ["1", "2", "3"];
docRef.update({
test: firebase.firestore.FieldValue.arrayUnion.apply(this, myArray)
});
Example For ECMAScript 6
using the spread argument
let myArray = ["1", "2", "3"];
docRef.update({
test: firebase.firestore.FieldValue.arrayUnion(...myArray)
});
When passing an array using either of the above methods, Firestore will only add new array elements to that do not already exist in the Firestore array.
For example, running the above, then running the following
let myArray = ["2", "3", "5", "7"];
docRef.update({
test: firebase.firestore.FieldValue.arrayUnion(...myArray)
});
would only add "5" and 7" to the array in Firestore. This works for an array of objects as well.
来源:https://stackoverflow.com/questions/53252265/firestore-pass-array-to-arrayunion