Search code examples
firebaseflutterfirebase-realtime-databasegoogle-cloud-firestore

Flutter - How to add a field to all documents in firebase collection


I am using flutter firebase. And I want a query to add a key and value to all documents in firebase collection.

I try to use batch write but it add a new documents having field. But not merge to existing documents.

var db= Firestore.instance();
var batch = db.batch();
batch.setData(
db.collection("users").document(),
{"status": "Approved"}
);

When I try to give document Id like document('id') it add only to that document.

I try many and watches YouTube videos but not able find still now. Please help me !


Solution

  • Create a dummy button on one of the pages in your app. Pressing the button should add the field in all documents of the particular collection.

    Here, I have used an IconButton to add an empty field called 'bio' in the 'users' collection.

    You can delete the button later after you've added the field in your documents because this is your (developer's) problem, and your app user does not need the button.

    IconButton(
                          onPressed: () {
                            FirebaseFirestore.instance
                                .collection('users')
                                .get()
                                .then(
                                  (value) => value.docs.forEach(
                                    (element) {
                                      var docRef = FirebaseFirestore.instance
                                          .collection('users')
                                          .doc(element.id);
    
                                      docRef.update({'bio': ''});
                                    },
                                  ),
                                );
                          },
                          icon: Icon(Icons.done),
                        ),