0

I am attempting to update the "likes" field for every document in a collection in Firebase. This operation must be done once every week, so we are using Firebase Cloud Functions to achieve this. As of now, the following code works to achieve this goal (in Web version 8 namespaced):

 await db.collection("events").get().then((querySnapshot) => {
      querySnapshot.forEach((doc) => {
          doc.ref.update({
              likes: 0
          });
      });

However, I would like to implement batch writes to make this operation scalable. I would also like to keep the bill generated from using Firebase to a minimum. How can this be implemented in this particular case? I have been looking through the Firebase Documentation in the Transactions and Batched Writes section, but have not found much help. The issue is that the document names must be known ahead of time according to the docs.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Roche
  • 155
  • 1
  • 12
  • 2
    Yes, you need know document IDs so that'll involve reading whole collection first (or just [reading document IDs using Admin SDK](https://stackoverflow.com/q/48947499/13130697)) and then using [batched writes](https://firebase.google.com/docs/firestore/manage-data/transactions#web-version-8_2) to update them back (500 in a batch). That still is N reads and N writes. Also checkout [Can Firestore update multiple documents matching a condition, using one query?](https://stackoverflow.com/questions/48947499/can-firestore-update-multiple-documents-matching-a-condition-using-one-query) – Dharmaraj Feb 26 '22 at 19:41
  • 2
    Batched writes are not necessarily that much more efficient than parallel individual writes. See https://stackoverflow.com/questions/58897274/what-is-the-fastest-way-to-write-a-lot-of-documents-to-firestore – Frank van Puffelen Feb 26 '22 at 20:23

0 Answers0