How to update a single field of all documents in firestore using flutter?

百般思念 提交于 2021-02-11 17:12:56

问题


I have a 100 user documents in database, and I have to update one field to 0 in all documents. How do we do it?


回答1:


Firestore doesn't offer a SQL-like "update where" command that updates everything at once, so you will have to:

  1. Query for the documents to update
  2. Iterate each DocumentSnapshot and get its DocumentReference object using the reference property
  3. For each document, update the field with its new value



回答2:


Try doing the following

  1. Query the documents to update
  2. Go through each DocumentSnapshot and get its DocumentReference object using the reference property and for each document, update the field with its new value
    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());
        }
      }

The code above simply updates all unread notification from false to true immediately the user clicks on the notification tray



来源:https://stackoverflow.com/questions/63321875/how-to-update-a-single-field-of-all-documents-in-firestore-using-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!