任何人都知道如何在Firestore事务中实现多个获取?
我有一系列Firestore引用,长度未知,保存在Firestore中。每个引用包含{count:number},我只想在每个引用中添加一个。要做到这一点,我非常有信心我需要使用事务,文档说我可以使用多个获取,但我不确定如何实现它。
我认为我需要获取每个引用,将现有计数存储在一个数组中,每个引用添加一个,然后将它们全部保存回Firestore。每次我试图实现这个我都失败了。在Firestore事务中使用多个gets的一个示例可能就是我需要的所有内容,但是在文档中没有,或者在我找到的任何地方都没有。
答案 0 :(得分:7)
您必须使用 Promise.all ,因为您需要迭代 arrayOfReferences 的每个firestore引用。
我为你做了一个例子并测试了它,只需按照下面的代码:
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 });
}));
});
}
要了解有关计数器在Firestore中的工作方式的更多信息,您可以阅读documentation。
答案 1 :(得分:1)
Firestore文档没有说明这一点,但答案隐藏在API参考中:https://cloud.google.com/nodejs/docs/reference/firestore/0.13.x/Transaction?authuser=0#getAll
您可以使用Transaction.getAll()
代替Transaction.get()
来获取多个文档。