简体   繁体   English

在 Firestore 中添加 map?

[英]Adding map in Firestore?

How can I append a new Map type in firestore?我怎样才能 append 在 firestore 中输入一个新的Map

void addUser() async {
    final us = _firestore.collection("users").doc(_search.text);
    us.update({
      "requests": (
        {_auth.currentUser?.email: rep}
      ),
    });
  }

Am using this method but the requests field in my firestore overwrites the previous one I want it to be appended.我正在使用此方法,但我的 Firestore 中的请求字段覆盖了我希望附加的前一个字段。 Any idea?任何的想法?

The update() method will always overwrite your previous field with the new one, so achieving this with one operation using the update() is not possible, however, you can always get the current field from the document, then update its value, then save it again in the document like this: update()方法将始终用新字段覆盖您以前的字段,因此不可能通过使用update()的一次操作实现此目的,但是,您始终可以从文档中获取当前字段,然后更新其值,然后再次将其保存在文档中,如下所示:

void addUser() async {
    final us = _firestore.collection("users").doc(_search.text);
    final currentDoc = await us.get(); // we get the document snapshot
    final docDataWhichWeWillChange = currentDoc.data() as Map<String, dynamic>; // we get the data of that document

    docDataWhichWeWillChange{"requests"]![_auth.currentUser?.email] = rep; // we append the new value with it's key 
    
    await us.update({
      "requests": docDataWhichWeWillChange["requests"],
    }); // then we update it again
  }

But you should use this after being aware that this method will make two operations in your database, a get() and update() .但是你应该在意识到这个方法将在你的数据库中进行两个操作之后使用它,一个get()update()

If you want to record multiple values, an array is an appropriate type.如果要记录多个值,数组是一种合适的类型。 So, you could use the .arrayUnion method to record multiple entries.因此,您可以使用.arrayUnion方法来记录多个条目。

final washingtonRef = db.collection("cities").doc("DC");

// Atomically add a new region to the "regions" array field.
washingtonRef.update({
  "regions": FieldValue.arrayUnion(["greater_virginia"]),
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM