I want to get some documents from Firestore. in my callable cloud function, instead of waiting getting document one by one, await one by one, I use Promise.all so I can get all documents faster, like this
const promises = []
upcomingEventIDs.forEach( upcomingEventIDs => {
const p = db.collection("events")
.where("eventID","==",upcomingEventIDs)
.where("isActive","==",true)
.where("hasBeenApproved","==",true)
.where("isCancelled","==",false)
.get()
promises.push(p)
})
const latestEventDataSnapshot = await Promise.all(promises)
and then I want to loop the document snapshots I just get, and here is the problem
latestEventDataSnapshot.docs.forEach( doc => { // <-- error in this line
})
I have an error
TypeError: Cannot read property ‘forEach’ of undefined
what is wrong in here ? what should I do to get the documents that I just get from Firestore ?
Advertisement
Answer
The get() method returns a Promise that resolves with a QuerySnapshot.
Since Promise.all() “returns a single Promise that resolves to an array of the results of the input promises”, latestEventDataSnapshot is an Array of QuerySnapshots and you need to loop over it, for example as follows:
const latestEventDataSnapshot = await Promise.all(promises)
latestEventDataSnapshot.forEach(querySnapshot => {
querySnapshot.docs.forEach(queryDocumentSnapshot => {
console.log(queryDocumentSnapshot.data());
//...
})
})