How to iterate through a Firestore snapshot documents while awaiting

北城以北 提交于 2021-01-07 04:01:13

问题


I have been trying to obtain a series of documents from firestore, reading them and acting accordingly depending on a series of fields. The key part is I want to wait for a certain process while working on each document. The official documentation presents this solution:

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

The problem with this solution is taht when you have a promise inside the forEach it won't await it before continuing, which I need it to. I have tried using a for loop:

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

When using this code Firebase alerts that 'docs.docs(...) is not a function or its return value is not iterable'. Any ideas on how to work around this?


回答1:


Note that your docs variable is a QuerySnapshot type object. It has an array property called docs that you can iterate like a normal array. It will be easier to understand if you rename the variable like this:

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
}



回答2:


I have found this solution.

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
        })
    })

As you can see this code stores the data in an extern array and only after this action it works with that data

I hope this helped you to solve the problem!



来源:https://stackoverflow.com/questions/63328123/how-to-iterate-through-a-firestore-snapshot-documents-while-awaiting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!