如何使用flutter更新Firestore中所有文档的单个字段?

时间:2020-08-09 02:13:25

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

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

3 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:0)

尝试执行以下操作

  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

答案 2 :(得分:0)

正如 @Doug 提到的,没有直接的方法,您必须查询数据,从 DocumentReference 获取 QueryDocumentSnapshot 并在其上调用 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',
  });
}