【问题标题】:Flutter and Firestore: How to update multiple specific documents from collection groupFlutter 和 Firestore:如何更新集合组中的多个特定文档
【发布时间】:2021-06-11 18:43:21
【问题描述】:

好的,所以我有多个相同的特定文档 ID,但每个 ID 用于不同的集合和用途。使用集合组,因为这些文档嵌套在子集合中,我能够找到这些文档并打印它们。我将如何使用其他数据同时更新所有这些文档中的特定字段?就我而言,尽管这些文档位于不同的集合中,但它们有一个名为 plastics 的字段,我想用 int 数据更新它们。

这是我用来检索这些文档并过滤以仅打印我特别需要的文档的代码:


                      final String uid = FirebaseAuth.instance.currentUser.uid;

                      

                      QuerySnapshot querySnapshot = await FirebaseFirestore
                          .instance
                          .collectionGroup("Members")
                          .get();

                      for (int i = 0; i < querySnapshot.docs.length; i++) {
                        var a = querySnapshot.docs[i];
                        if (a.id == uid) {
                          print(a.id);
                        }
                      }

这里还有一些我之前用于更新单个文档中的字段的代码,但并不是所有这些都像我在这种情况下需要的那样。

Future<bool> addPlastic(String amount) async {
  try {
    String uid = auth.currentUser.uid;
    var value = double.parse(amount);
    DocumentReference documentReference =
        FirebaseFirestore.instance.collection('some collection').doc(some document);

    FirebaseFirestore.instance.runTransaction((transaction) async {
      DocumentSnapshot snapshot = await transaction.get(documentReference);
      if (!snapshot.exists) {
        documentReference.set({'plastics': value});
        return true;
      }
      double newAmount = snapshot.data()['plastics'] + value;
      transaction.update(documentReference, {'plastics': newAmount});
      return true;
    });
  } catch (e) {
    return false;
  }
}

【问题讨论】:

    标签: firebase flutter google-cloud-firestore


    【解决方案1】:

    您有两个选择,要么循环遍历所有集合和子集合(乏味),要么将列表文档引用存储在其中一个文档中,并通过遍历所有这些文档引用来更改数据(更好的选择)。如果您需要有关如何执行此操作的代码或指南,请告诉我。

    编辑

    要使用文档引用部分,首先,在创建文档时,你必须这样做

    document(id).set({
    "value1":"oko",
    "plastic":"240",
    //And the rest of your values
    "otherSnapshots":[/*Your list of documentSnapshots with the same ID. Update it in this whenever you have new one by following the next snippet*/]
    })
    

    当你创建一个新文档时,导航到这个并添加文档参考

    snapshot.reference.update({
            'otherSnapshots':FieldValue.arrayUnion([/*Document Reference*/])
          }); 
    

    下一次,当你想更新所有这些时,使用这个字段,循环遍历它,然后你会得到所有的文档引用。我无法创建一个代码,您可以直接将粘贴复制到您的代码中,而无需查看您如何存储数据

    【讨论】:

    • 感谢您的输入,我仍在学习,但代码示例将对第二个选项有所帮助
    猜你喜欢
    • 1970-01-01
    • 2021-05-12
    • 2019-04-11
    • 2022-01-07
    • 2020-03-08
    • 1970-01-01
    • 2023-02-10
    • 2021-11-18
    • 2020-10-03
    相关资源
    最近更新 更多