颤振| 如何将数据添加到Firestore中的现有文档

STE*_*LUS 7 dart firebase firebase-authentication flutter google-cloud-firestore

我正在使用Firestore存储我的flutter应用程序的数据,并且我创建了一个函数,该功能可在用户登录My Firestore数据库后自动在firestore中创建文档

现在,我希望用户在填写此表单时将数据添加到用户电子邮件所在的同一文档中。

[ RaisedButton(
              child: Text("Submit"),
              onPressed: () {
               final CollectionReference users = Firestore.instance.collection('users');
                Firestore.instance
                    .runTransaction((Transaction transaction) async {
                  CollectionReference reference =
                  Firestore.instance.collection('users');

                  await reference
                      .add({"fullname": nameController.text, "PhoneNumber": phoneController.text, "adresse": adressController.text});
                  nameController.clear();
                  phoneController.clear();
                  adressController.clear();

                });},][2]
Run Code Online (Sandbox Code Playgroud)

我尝试了此代码,但它添加了新文档。

Vin*_*mar 19

在更新数据库之前指定文档名称。

Firestore.instance
  .collection('Products')
    .document('Apple')
      .updateData({
        'price': 120, 
        'quantity': 15
      });
Run Code Online (Sandbox Code Playgroud)

这里我的价格和数量数据是数字。如果你的是Strings 把String值放在那里。

  • setData 将删除现有文档并创建一个新文档。问题不在于那个。这是关于向现有文档添加数据。 (5认同)

Tre*_*ree 7

最佳实践是使用事务。确保文档引用是对您要更新的文件的引用。

            Firestore.instance.runTransaction((transaction) async {
              await transaction.update(
                  documentReference, data);
            };
Run Code Online (Sandbox Code Playgroud)

它将确保更新按顺序进行,以防有许多客户端在执行此操作。

在并发编辑的情况下,Cloud Firestore 会再次运行整个事务。例如,如果一个事务读取了文档,而另一个客户端修改了这些文档中的任何一个,Cloud Firestore 会重试该事务。此功能可确保事务在最新且一致的数据上运行。

更多信息在这里


小智 6

试试.setData({"fullname": nameController.text, "PhoneNumber": phoneController.text, "adresse": adressController.text}, merge: true)