Home > Back-end >  How to use batch update in firestore web version-9?
How to use batch update in firestore web version-9?

Time:08-04

In my nuxt project, I want to update some values in my firestore collection but i get mistakes

  const batch = writeBatch(firestore);

  const data = query(collection(firestore, `notifications`, `${uid}/news`));

  const querySnapshot = await getDocs(data);

  querySnapshot.forEach(doc => {
    if (doc.data().type === 'like') {
      batch.update(doc, { seen: true });
    }

     batch.commit();
  });

CodePudding user response:

You need to pass a DocumentReference as first argument of the update() method, and not a QueryDocumentSnapshot.

You also need to commit the batch outside of the loop: you can commit the batch only once. This is what indicates the error message you added as a comment to your question.

Finally, note that you don’t need to use the query() method since you want to loop over the entire collection.

 const batch = writeBatch(firestore);

 const data = collection(firestore, `notifications`, `${uid}/news`);

 const querySnapshot = await getDocs(data);

 querySnapshot.forEach(doc => {
   if (doc.data().type === 'like') {
     batch.update(doc.ref, { seen: true });
   }
  });

  batch.commit();
 
  • Related