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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With