简体   繁体   中英

Flutter and Firestore: How to update multiple specific documents from collection group

Okay, so I have multiple specific document ids that are all the same, but each one is used for different collections and purposes. Using a collection group as these documents are nested in subcollections, I was able to locate these documents and print them. How would I go about updating a specific field in all of these documents at the same time with some other data? In my case these documents despite being in different collections have a field called, plastics and I want to update them with int data.

Here is the code I used to retrieve these documents and filter to only print the one's I specificly need:


                      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);
                        }
                      }

Also here is some code I've used before for updating a field in a single document, but not all of them like I need to in this case.

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;
  }
}

You have two options, either loop through all the collections and sub collections (tedious), or store a list document references in one of the documents and change the data by looping through all of these document references ( better option). If you need some code or guidelines on how to do that, let me know.

EDIT

To use the document reference part, first, when creating the document, you have to do something like this

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*/]
})

When you create a new document, navigate to this and add in the document Reference by

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

And next time, when you want to update all of them, use this field, loop through it and then you will get all the document references. I cannot create a code that you can directly copy paste into your code without seeing how u store data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM