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)
});
When it comes to the official documentation regarding how to update elements in an array in Firestore, it says that: If your document contains an array field, you can use arrayUnion() and arrayRemove() to add and remove elements. arrayUnion() adds elements to an array but only elements not already present.
Firestore lets you write a variety of data types inside a document, including strings, booleans, numbers, dates, null, and nested arrays and objects.
Is there any way to update a specific index from the array in Firestore? No, there is not! This is not possible because if you want to perform an update, you need to know the index of that particular element. When talking about Cloud Firestore arrays, the things are different that you might think.
A FieldValue is a union type that may contain a primitive (like a boolean or a double), a container (e.g. an array), some simple structures (such as a Timestamp ) or some Firestore-specific sentinel values (e.g. ServerTimestamp ) and is used to write data to and read data from a Firestore database.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With