Firestore - Pass Array To arrayUnion()

扶醉桌前 提交于 2020-08-27 02:17:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!