我正在尝试为 Firebase 编写一个函数,当更新另一种类型的文档时,该函数会更新特定集合内的所有文档。
functions.firestore.document('/accounts/{accountId}/resources/{resourceId}')
.onUpdate((change, context) => {
const resource = context.params.resourceId;
admin.firestore().collection('/accounts/'+account+'/tasks')
.where('resourceId', '=', resource).get().then(snapshot => {
snapshot.forEach(doc => {
doc.update({
fieldA: 'valueA',
fieldB: 'valueB'
});
});
return true;
})
.catch(error => {
console.log(error);
});
});
这不起作用,但我不知道该怎么做,这是我第一次为 Firebase 制作函数。
最佳答案
以下应该可以解决问题:
functions.firestore.document('/accounts/{accountId}/resources/{resourceId}')
.onUpdate((change, context) => {
const resource = context.params.resourceId;
return admin.firestore().collection('/accounts/'+account+'/tasks')
.where('resourceId', '=', resource).get().then(snapshot => {
const promises = [];
snapshot.forEach(doc => {
promises.push(doc.ref.update({
fieldA: 'valueA',
fieldB: 'valueB'
}));
});
return Promise.all(promises)
})
.catch(error => {
console.log(error);
return null;
});
});
注意:
return admin.firestore() 中的
return
....- 在
forEach()
中你会得到QueryDocumentSnapshots
所以你必须做doc.ref.update()
- 使用
Promise.all()
因为您并行执行多个异步方法。
正如 Doug 在评论中建议的那样,您应该观看 Firebase 视频系列中有关“JavaScript Promises”的 3 个视频:https://firebase.google.com/docs/functions/video-series/
关于javascript - Firebase 函数 : update all documents inside a collection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53836195/