Home > database >  Firebase Firestore update a field in all documents(V9)
Firebase Firestore update a field in all documents(V9)

Time:11-26

I want to update notf_unread : true for all documents in users collection in firebase firestore for web

How can i achieve this..

Firestore

CodePudding user response:

If you want to update all the documents within your collection. You must create a query with your collection reference and iterate all the results of the query. See sample code below:

version 8 (namespaced):

var db = firebase.firestore();

db.collection("users")
    .get()
    .then((querySnapshot) => {
        querySnapshot.forEach((doc) => {
          doc.ref.update({
              notf_unread: false
          })
          .then(() => {
              console.log("Document successfully updated!");
          })
          .catch((error) => {
              // The document probably doesn't exist.
              console.error("Error updating document: ", error);
          });
        });
    })
    .catch((error) => {
        console.log("Error getting documents: ", error);
    });

version 9 (modular):

const q = query(collection(db, 'users'))

const querySnapshot = await getDocs(q);

querySnapshot.forEach((doc) => {
    updateDoc(doc.ref, {
        notf_unread: false
    })
    .then(() => {
        console.log("Document successfully updated!");
    })
    .catch((error) => {
        // The document probably doesn't exist.
        console.error("Error updating document: ", error);
    });
})

For more information, you may visit this documentations:

  • Related