[英]How to append an array into an array field in firestore?
I have a collection named Users
with a field named friendEmails
which is an array that contains Strings.我有一个名为
Users
的集合,其中包含一个名为friendEmails
的字段,它是一个包含字符串的数组。
I have a document with friendEmails = {joe@gmail.com, dan@gmail.com}
, and I want to append newEmails = {mat@gmail.com, sharon@gmail.com}
to it.我有一个文件
friendEmails = {joe@gmail.com, dan@gmail.com}
,我想 append newEmails = {mat@gmail.com, sharon@gmail.com}
到它。
The only options I know for this are:我知道的唯一选择是:
Reading the friendEmails
array first, then adding the union of it and newEmails
to the document.首先读取
friendEmails
数组,然后将其与newEmails
的并集添加到文档中。
Iterating over the elements of newEmails
(let's and each iteration doing: myCurrentDocumentReference.update(FieldValue.arrayUnion, singleStringElement);
newEmails
的元素(让我们和每次迭代做: myCurrentDocumentReference.update(FieldValue.arrayUnion, singleStringElement);
(Since FieldValue.arrayUnion
only lets me pass comma-separated elements, and all I have is an array of elements). (因为
FieldValue.arrayUnion
只允许我传递逗号分隔的元素,而我所拥有的只是一个元素数组)。
These two options aren't good since the first requires an unnecessary read operation (unnecessary since FireStore seems to "know" how to append items to arrays), and the second requires many write operations.这两个选项都不好,因为第一个需要不必要的读取操作(不需要,因为 FireStore 似乎“知道”如何将 append 个项目写入数组),第二个需要许多写入操作。
I'd expect Firestore to give me the option to append an entire array, and not just single elements.我希望 Firestore 给我选择 append 整个数组,而不仅仅是单个元素。
Something like this:像这样:
ArrayList<String> newEmails = Arrays.asList("mat@gmail.com", "sharon@gmail.com");
void appendNewArray() {
FirebaseFirestore firestore = FirebaseFirestore.getInstance();
firestore.collection("Users").document("userID").update("friendEmails", FieldValue.arrayUnion(newEmails));
}
Am I missing something?我错过了什么吗? Wouldn't this be a sensible operation to expect?
这难道不是一个明智的操作吗?
How else could I go about performing this action, without all the unnecessary read/write operations?如果没有所有不必要的读/写操作,我 go 还能如何执行此操作?
You can add multiple items to an array field like this using FieldValue.arrayUnion() as the value of a field update:您可以像这样使用FieldValue.arrayUnion()作为字段更新的值将多个项目添加到数组字段:
docRef.update("friendEmails", FieldValue.arrayUnion(email1, email2));
If you need to convert an ArrayList to an array for use with varargs arguments :如果您需要将 ArrayList 转换为与可变参数 arguments 一起使用的数组:
docRef.update("friendEmails", FieldValue.arrayUnion(
newEmails.toArray(new String[newEmails.size()])
));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.