20

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)
});
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Matthew Rideout
  • 7,330
  • 2
  • 42
  • 61

1 Answers1

33

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.

Matthew Rideout
  • 7,330
  • 2
  • 42
  • 61
  • 8
    Thank you for this. Docs only show example for adding a single element, Firebase team should consider adding this. – Jo E. May 09 '19 at 08:59
  • 2
    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. – J. Adam Connor Nov 02 '19 at 23:42
  • 3
    Thanks! I was baffled, especially since the [documentation](https://firebase.google.com/docs/reference/js/firebase.firestore.FieldValue#static-array-union) explicitly lists`[]` as an argument to `arrayUnion`. – Tim Erickson Mar 04 '20 at 16:12
  • any kotlin syntax? – Bhavesh Hirpara Jul 29 '20 at 18:56
  • 1
    @TimErickson - The documentation says `arrayUnion(...elements: any []) : FieldValue`, which is correct. This is a ["Rest parameter"](https://www.typescriptlang.org/docs/handbook/functions.html#rest-parameters); it is essentially multiple params. You must pass values individually, or using spread, and it is received grouped together as an array. – charles-allen Jun 22 '21 at 05:33