21

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 Answer 1

37

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you for this. Docs only show example for adding a single element, Firebase team should consider adding this.
I guess any competent programmer should be able to figure out that spread should do this, but an example with an array seems more common than a single string. Agree that Firebase team should add to docs.
Thanks! I was baffled, especially since the documentation explicitly lists[] as an argument to arrayUnion.
any kotlin syntax?
@TimErickson - The documentation says arrayUnion(...elements: any []) : FieldValue, which is correct. This is a "Rest parameter"; it is essentially multiple params. You must pass values individually, or using spread, and it is received grouped together as an array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.