How to iterate through a Firestore snapshot documents while awaiting

Viewed 2265

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?

2 Answers

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
}

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!

Related