首页 > 解决方案 > 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 制作函数。

标签: javascriptfirebasegoogle-cloud-firestoregoogle-cloud-functions

解决方案


以下应该可以解决问题:

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;
    });
});

笔记:

  1. return在_return admin.firestore()....
  2. 那在forEach()你得到 QueryDocumentSnapshots所以你必须做doc.ref.update()
  3. 使用Promise.all()因为您并行执行多个异步方法。

正如 Doug 在评论中建议的那样,您应该观看 Firebase 视频系列中关于“JavaScript Promises”的 3 个视频:https ://firebase.google.com/docs/functions/video-series/


推荐阅读