javascript - 如何在等待时遍历 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(...) 不是函数或其返回值不可迭代”。关于如何解决这个问题的任何想法?
解决方案
请注意,您的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
}
推荐阅读
- python - 用于 Youtube 的 Python Selenium Opera - 出现错误
- javascript - 如何区分 Javascript 中的列表和对象?
- java - 在java中使用文件IO来读写一个我自己的集合类
- firebase - 为什么 Firebase 需要 Google 密钥才能登录?
- r - 如何调整 Shiny 中生成的图形的图例
- c++ - 运行“make -j”时的构建问题-“je_malloc”属性指令被忽略
- curl - ubuntu 20.10 上的 curl 损坏 curl_url_set 未定义
- reactjs - 如何在 grpc-web 中使用 TLS?
- reactjs - 上传带有图片的表单formik
- javascript - 未找到 lambda 层的模块(AWS、JavaScript)