首页 > 解决方案 > 如何在等待时遍历 Firestore 快照文档

问题描述

我一直在尝试从 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(...) 不是函数或其返回值不可迭代”。关于如何解决这个问题的任何想法?

标签: javascriptnode.jsfirebasegoogle-cloud-firestoregoogle-cloud-functions

解决方案


请注意,您的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
}

推荐阅读