问题
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.
回答1:
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.
回答2:
The Firestore doc doesn't say this, but the answer is hidden in the API reference: https://cloud.google.com/nodejs/docs/reference/firestore/0.13.x/Transaction?authuser=0#getAll
You can use Transaction.getAll()
instead of Transaction.get()
to get multiple documents.
来源:https://stackoverflow.com/questions/47949573/firestore-transaction-implementing-multiple-gets