Firestore transaction, implementing multiple gets

妖精的绣舞 提交于 2019-12-23 07:44:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!