javascript - Firebase 函数:更新集合中的所有文档
问题描述
我正在尝试为 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
在_return admin.firestore()....
- 那在
forEach()
你得到QueryDocumentSnapshots
所以你必须做doc.ref.update()
- 使用
Promise.all()
因为您并行执行多个异步方法。
正如 Doug 在评论中建议的那样,您应该观看 Firebase 视频系列中关于“JavaScript Promises”的 3 个视频:https ://firebase.google.com/docs/functions/video-series/
推荐阅读
- ios - Function from Swift class can't be seen by Objective-C class
- android - Click on button == button appears in random location
- django - 如何对 django 中的计算变量求和?
- java - 如何在 Kotlin 中使用现有的比较器
- sql-server - 从链接表查询插入本地表很慢
- python - 遍历 2 个变量以创建标志
- angular - Firestore Service Worker 和推送通知
- javascript - 有没有办法传递一个变量来评估或从评估中加载一个 json 文件?
- r - R中条形图的聚合分组
- bazel - Bazel query that doesn't follow all select branches