[英]Force the Firestore array to merge with the value that's already a part of the array
There is a method arrayUnion()
that we use to add additional element to the existing array.有一种方法
arrayUnion()
可用于向现有数组添加其他元素。 When adding the value that already existed in the array, however, it's not going to merge, and it's just going to persist one element instead of two.然而,当添加数组中已经存在的值时,它不会合并,它只会保留一个元素而不是两个。
Example:
Existing array = [2]
ArrayUnion([2])...
Resultant array [2]
Example 2;
Existing array = [3];
ArrayUnion([2])...
Resultant Array = [3, 2];
How can I make it work so that the resultant array in the first example would be [2, 2]?我怎样才能让它工作,以便第一个示例中的结果数组为 [2, 2]?
From the documentation for arrayUnion
:从
arrayUnion
的文档中:
Returns a special value that can be used with
set()
orupdate()
that tells the server to union the given elements with any array value that already exists on the server.返回一个可以与
set()
或update()
一起使用的特殊值,它告诉服务器将给定元素与服务器上已存在的任何数组值合并。 Each specified element that doesn't already exist in the array will be added to the end.数组中尚不存在的每个指定元素都将添加到末尾。 If the field being modified is not already an array it will be overwritten with an array containing exactly the specified elements.
如果被修改的字段还不是一个数组,它将被一个完全包含指定元素的数组覆盖。
The arrayUnion
operator ensures that each unique value exists at most once in the array. arrayUnion
运算符确保每个唯一值在数组中最多存在一次。 There is no way to add a duplicate value with arrayUnion
.无法使用
arrayUnion
添加重复值。
If you want to add a duplicate value, you'll have to read the entire array, modify it on the client, and write it back.如果要添加重复值,则必须读取整个数组,在客户端修改它,然后写回。
I found a workaround because I was facing the same issue.我找到了解决方法,因为我遇到了同样的问题。 I don't know how well this will translate in the long run, but what I did is to add a random decimal at the end of the number.
我不知道从长远来看这会翻译成什么样,但我所做的是在数字末尾添加一个随机小数。
FieldValue.arrayUnion(`${value}.${rand}`)
I know it may not be a proper solution, but hopefully it is not much of an issue when querying the data from my App.我知道这可能不是一个合适的解决方案,但希望从我的应用程序查询数据时这不是什么大问题。 I'll omit the decimals there.
我会省略那里的小数点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.