Jus*_*s10 8 transactions google-cloud-firestore
任何人都知道如何在Firestore事务中实现多个获取?
我有一系列Firestore引用,长度未知,保存在Firestore中.每个引用包含{count:number},我只想在每个引用中添加一个.为此,我非常有信心我需要使用事务,文档说我可以使用多个获取,但我不确定如何实现它.
我认为我需要获取每个引用,将现有计数存储在一个数组中,每个引用添加一个,然后将它们全部保存回Firestore.每次我试图实现这个我都失败了.在Firestore事务中使用多个gets的一个示例可能就是我需要开始的所有内容,但是在文档中没有,或者在我发现的任何地方都没有.
您必须使用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 });
}));
});
}
Run Code Online (Sandbox Code Playgroud)
要了解有关计数器如何在Firestore中工作的更多信息,您可以阅读文档.