To query a Firestore collection, you need to use the get()
method.
Doing const postsCol = await admin.firestore().collection('posts')
will not query the database, it just defines a CollectionReference
. The same for postsCol.where('sentBy', '==', elem)
or postsCol.orderBy("sentAt", "desc").limit(5)
: they define a Query
but do not fetch the database.
Each query to a collection with the get()
method is an asynchronous operation: the get()
method returns a Promise
which resolves with the results of the query.
Since you want to trigger several queries in parallel, you should use Promise.all()
, as follows:
const queries = [];
idsList.forEach(elem => {
queries.push(admin.firestore().collection('posts').where('sentBy', '==', elem).get());
})
Promise.all(queries)
.then(results => {
//Do whatever you want with the results array which is an array of QuerySnapshots
//See https://firebase.google.com/docs/reference/js/firebase.firestore.QuerySnapshot.html
})
Note: if you use this code in a Cloud Function, don't forget to return the Promises returned by the asynchronous operations (including the promise returned by Promise.all()
).