fds18
fds18

Reputation: 118

How to iterate through a Firestore snapshot documents while awaiting

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?

Upvotes: 6

Views: 3414

Answers (2)

Doug Stevenson
Doug Stevenson

Reputation: 317372

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
}

Upvotes: 21

Francesco Bollini
Francesco Bollini

Reputation: 13

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!

Upvotes: -2

Related Questions