【问题标题】:FLUTTER | How to add data to an existing document in firestore颤振 |如何将数据添加到 Firestore 中的现有文档
【发布时间】:2018-11-06 14:54:23
【问题描述】:

我正在使用 firestore 来存储我的 Flutter 应用程序的数据,并且我制作了一个功能,在用户登录后自动在 firestore 中创建一个文档 My Firestore database

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

[ 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]

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

【问题讨论】:

  • 您的问题在于您要更新什么文件。您需要正确引用您的文件。你知道你要更新什么文件吗?

标签: firebase dart firebase-authentication google-cloud-firestore flutter


【解决方案1】:

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

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

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

【讨论】:

  • 还有instance.collection('users').document('${user.id}').setData({"fullname": nameController.text, "PhoneNumber": phoneController.text, "adresse": adressController.text}); 的选项
  • setData 将删除现有文档并创建一个新文档。问题不在于那个。这是关于向现有文档添加数据。
【解决方案2】:

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

            Firestore.instance.runTransaction((transaction) async {
              await transaction.update(
                  documentReference, data);
            };

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

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

更多信息here

【讨论】:

    【解决方案3】:

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

    【讨论】:

    • updateData() 对我不起作用。我的意思是它有效,但它取代了整个数据。 setData()merge: true 非常适合我。
    【解决方案4】:

    2021 年更新:

    您需要更新数据以将其添加到现有文档中。

    var collection = FirebaseFirestore.instance.collection('users');
    collection 
        .doc('doc_id') // <-- Doc ID where data should be updated.
        .update({'age' : 20}) // <-- New data
        .then((_) => print('Updated'))
        .catchError((error) => print('Update failed: $error'));
    

    【讨论】:

      猜你喜欢
      • 2020-10-28
      • 1970-01-01
      • 1970-01-01
      • 2021-06-27
      • 2019-02-25
      • 2020-10-23
      • 1970-01-01
      • 1970-01-01
      • 2021-12-12
      相关资源
      最近更新 更多