如何在等待时迭代 Firestore 快照文档

fds*_*s18 3 javascript node.js firebase google-cloud-functions google-cloud-firestore

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

const docs = await firestore.collection(...).where(...).where(...).get()
    docs.forEach(await (doc) => {
      //something
    })
Run Code Online (Sandbox Code Playgroud)

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

const docs = await firestore.collection(...).where(...).where(...).get()
            for(var doc of docs.docs()) {
      //something
            }
Run Code Online (Sandbox Code Playgroud)

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

Dou*_*son 11

请注意,您的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
}
Run Code Online (Sandbox Code Playgroud)