【问题标题】:How to update a single field of all documents in firestore using flutter?如何使用flutter更新firestore中所有文档的单个字段?
【发布时间】:2020-11-28 23:26:10
【问题描述】:

我在数据库中有 100 个用户文档,我必须将所有文档中的一个字段更新为 0。我们该怎么做?

【问题讨论】:

    标签: database firebase flutter google-cloud-firestore document


    【解决方案1】:

    Firestore 不提供类似 SQL 的“update where”命令来一次更新所有内容,因此您必须:

    1. 查询要更新的文档
    2. 迭代每个DocumentSnapshot 并使用reference property 获取其DocumentReference 对象
    3. 对于每个文档,update 具有新值的字段

    【讨论】:

      【解决方案2】:

      正如@Doug 所说,没有直接的方法,您必须查询数据,从QueryDocumentSnapshot 获取DocumentReference 并在其上调用update

      var collection = FirebaseFirestore.instance.collection('collection');
      var querySnapshots = await collection.get();
      for (var doc in querySnapshots.docs) {
        await doc.reference.update({
          'single_field': 'newValue',
        });
      }
      

      【讨论】:

      • 为我工作。谢谢:)
      【解决方案3】:

      尝试执行以下操作

      1. 查询要更新的文档
      2. 遍历每个DocumentSnapshot 并使用引用属性获取其DocumentReference 对象,并为每个文档更新字段的新值
          void updateNotificationCount() async {
              FirebaseUser _currentUser = await FirebaseAuth.instance.currentUser();
              String authid = _currentUser.uid;
              var snapshots =
                  activityFeedRef.document(authid).collection('feedItems').snapshots();
              try {
                await snapshots.forEach((snapshot) async {
                  List<DocumentSnapshot> documents = snapshot.documents;
          
                  for (var document in documents) {
                    await document.reference.updateData(<String, dynamic>{
                      'seen': true,
                    });
                  }
                });
              } catch (e) {
                print(e.toString());
              }
            }
      

      上面的代码只是在用户点击通知托盘时立即将所有未读通知从 false 更新为 true

      【讨论】:

        猜你喜欢
        • 2020-02-11
        • 1970-01-01
        • 2019-09-24
        • 2022-11-25
        • 2021-12-14
        • 2019-07-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多