Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore - Pass Array To arrayUnion()

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)
});
like image 659
Matthew Rideout Avatar asked Nov 11 '18 19:11

Matthew Rideout


People also ask

How do you update an array of objects in firestore?

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.

Can I store an array in Firestore?

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?

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.

What is FieldValue in firebase?

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.


1 Answers

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.

like image 105
Matthew Rideout Avatar answered Sep 18 '22 16:09

Matthew Rideout