javascript - Firebase 函数 : update all documents inside a collection

标签 javascript firebase google-cloud-platform google-cloud-firestore google-cloud-functions

我正在尝试为 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;
    });
});

注意:

  1. return admin.firestore() 中的return....
  2. forEach() 中你会得到 QueryDocumentSnapshots所以你必须做 doc.ref.update()
  3. 使用 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/

相关文章:

javascript - 当一切都解决后,在页面加载时发布事件

azure - k8s 使用来自不同命名空间的 secret

google-cloud-platform - 有没有办法在模拟服务帐户时使用 gsutil?

javascript - Vue.js 条件语句

php - 使用 PHP、JS、CSS 和 HTML 创建类似跳棋的实时 Web 应用程序?

javascript - 如何避免嵌套 Promise 从 Firestore 读取并等待所有解析?

swift - 传递 Firebase 数据库引用数据

javascript - Firebase Web - currentUser 返回 null

firebase - Firebase 是否会影响生产应用程序的性能

javascript - 如何使用 nunjucks 和express 应用程序添加页面特定脚本?