Skip to content Skip to sidebar Skip to footer

Firestore: How To Correctly Update Multiple Docs With A Query

Base on this: Can Firestore update multiple documents matching a condition, using one query? I do below but not very sure why I am getting this error: doc.update is not a function

Solution 1:

The doc itself is not the reference to the document. It's a DocumentSnapshot which has a property ref which is a DocumentReference. Try this:

let db = firebase.firestore()
db.collection('posts')
  .where('uid', '==', userId)
  .get()
  .then(async (snapshots) => {
    const updates = []
    snapshots.forEach((doc) =>
      updates.push(doc.ref.update({
        username: username,
      }))  
    )
    await Promise.all(updates)
  })

You can also use a batch write instead of pushing separate update promises.


Solution 2:

Update: See the answer provided by Dharmaraj for a more simple, straightforward answer. I didn't consider using the .ref property as he suggests, which makes a lot of sense.

Also, my answer assumed the userID was equal to the document ID, which actually wasn't the case in this scenario. Using a query is needed when the document ID and the userID are not equal.


The querySnapshot.forEach() function passes a "QueryDocumentSnapshot" to the callback, and this QueryDocumentSnapshot does not have the update() method available.

From the docs: "A Query refers to a Query which you can read or listen to. You can also construct refined Query objects by adding filters and ordering."
Notice the specification "read" and "listen". So if you want to write to a document, you will need to use something besides a query.

The update() method is available on DocumentReference. (If you read the quick description on the DocumentReference you'll notice it does specify 'write' as a use-case) So if we rewrote your code above to get a DocumentReference rather than a query it would look something like this:

let db = firebase.firestore();

// grabbing the DocumentReference that has a document id equal to userID
let userRef = db.collection('posts').doc(userID); 

// update that document
userRef.update({username: username})

Here I'm just getting the DocumentReference using the .doc() method and storing the value in userRef. Then I can update that document with .update().

I hope this helped!


Post a Comment for "Firestore: How To Correctly Update Multiple Docs With A Query"