如何动态地将地图数组添加到cloud firestore中?

Ama*_*ary 2 firebase flutter google-cloud-firestore

我添加了这样的数据,

await firestoreSave.collection('chat').doc().set({
      'buyer_id': "76QlZL2IbADZBnvbofN3",
      'book_id':"N5xlvDcWC5ffwdKWLA6DfF9FcfD2",
      'seller_id': "ranjit",
      "messages": [
        {"message": "What is up", "timeStamp": "Dec 12", "type": userId}
      ]
    }).catchError((onError) {
      print(
          "you have a error");
    });
Run Code Online (Sandbox Code Playgroud)

现在,如果我必须更新该messages字段。只需添加另一个具有相同键但不同值的地图,我该怎么做?
我尝试使用update,但我只能弄清楚在上一个地图中添加另一个字段,但我必须在数组中添加另一个地图。
我怎样才能做到呢?

osa*_*xma 5

更新现有数据有两种方法:

update(data)仅当文档存在时,才会更新给定字段。如果文档不存在,它将返回错误。

usingset(data, SetOptions(merge: true))将更新给定字段并合并它们,如果文档不存在,它也会创建该文档。

现在,如果您想向数组添加值而不更新其他字段,则必须使用FieldValue.arrayUnionset 或 update:

firestoreSave.collection('chat').doc().set({
      "messages": FieldValue.arrayUnion(
        [{"message": "What is up", "timeStamp": "Dec 12", "type": userId}]
      )
    }, SetOptions(merge: true))
Run Code Online (Sandbox Code Playgroud)

请注意,FieldValue.arrayUnion仅添加唯一值,并且它不适用于嵌套数组,这意味着您将无法使用它来更新消息映射内的任何字段。

另外,正如 @Renaud 在评论中提到的,您也可以一次添加多个值,例如:

firestoreSave.collection('chat').doc().set({
          "messages": FieldValue.arrayUnion(
            [{"message": "What is up", "timeStamp": "Dec 12", "type": userId}, 
             {"message": "What's new", "timeStamp": "Dec 12", "type": userId},
            ],
          ),
        }, SetOptions(merge: true))
Run Code Online (Sandbox Code Playgroud)