【问题标题】:How to iterate through a Firestore snapshot documents while awaiting如何在等待时遍历 Firestore 快照文档
【发布时间】:2020-11-29 08:17:15
【问题描述】:

我一直在尝试从 firestore 获取一系列文档,阅读它们并根据一系列字段采取相应的行动。关键部分是我想在处理每个文档时等待某个过程。官方文档介绍了这个解决方案:

const docs = await firestore.collection(...).where(...).where(...).get()
    docs.forEach(await (doc) => {
      //something
    })

这个解决方案的问题在于,当你在 forEach 中有一个承诺时,它不会在继续之前等待它,我需要它。我尝试过使用 for 循环:

const docs = await firestore.collection(...).where(...).where(...).get()
            for(var doc of docs.docs()) {
      //something
            }

使用此代码时,Firebase 会提醒“docs.docs(...) 不是函数或其返回值不可迭代”。关于如何解决这个问题的任何想法?

【问题讨论】:

    标签: javascript node.js firebase google-cloud-firestore google-cloud-functions


    【解决方案1】:

    我找到了这个解决方案。

    const docs = [];
    
    firestore.collection(...).where(...).get()
        .then((querySnapshot) => {
            querySnapshot.docs.forEach((doc) => docs.push(doc.data()))
        })
        .then(() => {
            docs.forEach((doc) => {
                // do something with the docs
            })
        })
    

    如您所见,此代码将数据存储在一个外部数组中,并且只有在此操作之后它才能使用该数据

    希望这能帮助您解决问题!

    【讨论】:

      【解决方案2】:

      请注意,您的 docs 变量是 QuerySnapshot 类型的对象。它有一个名为docs 的数组属性,您可以像普通数组一样对其进行迭代。如果你像这样重命名变量会更容易理解:

      const querySnapshot = await firestore.collection(...).where(...).where(...).get()
      for (const documentSnapshot of querySnapshot.docs) {
          const data = documentSnapshot.data()
          // ... work with fields of data here
          // also use await here since you are still in scope of an async function
      }
      

      【讨论】:

      • 我刚刚测试了这个方法,效果很好,我的错误是使用 .docs() 而不是 .docs
      • 在 Stack Overflow 上习惯使用左侧的按钮来投票和接受有用的答案作为正确答案。
      猜你喜欢
      • 1970-01-01
      • 2019-08-02
      • 2020-09-26
      • 2020-12-12
      • 2022-01-25
      • 2021-09-27
      • 2020-10-12
      • 2023-03-19
      • 1970-01-01
      相关资源
      最近更新 更多