Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore transaction, implementing multiple gets

Anyone know how to implement multiple gets in a Firestore Transaction?

I have an array of Firestore References, of an unknown length, saved in Firestore. Each reference contains {count: number} and I just want to add one to each reference. To do this I am pretty confident I need to use transactions, and the docs say I can use multiple gets, but I'm not sure how to implement it.

I would think I need to get each reference, store the existing counts in an array, add one to each, then save them all back to Firestore. Every time I've tried to implement this I fail. An example of using multiple gets in a Firestore Transaction is probably all I need to get going, but none exist in the docs, or anywhere online as far as I could find.

like image 734
Jus10 Avatar asked Dec 23 '17 03:12

Jus10


1 Answers

You have to use Promise.all because you need to iterate each firestore reference of the arrayOfReferences.

I made a example for you and tested it, just follow the code below:

setCount(arrayOfReferences){
  return this.db.runTransaction(t => {
    return Promise.all(arrayOfReferences.map(async (element) => {
      const doc = await t.get(element);
      const new_count = doc.data().count + 1;
      await t.update(element, { count: new_count });
    }));
  });
}

To get to know more about how counters work in Firestore, you can read the documentation.

like image 76
Mateus Forgiarini da Silva Avatar answered Sep 19 '22 14:09

Mateus Forgiarini da Silva