dhammani
dhammani

Reputation: 141

Is there a way to query a Firestore Collection with many 'where' in a loop?

I would like to make a query on a collection of documents, each document contain an id that is in an array. The query should be dynamic because the ids in the array change frequently. I've tried this but it doesn't work

const postsCol = await admin.firestore().collection('posts')
idsList.forEach(elem => {
  postsCol.where('sentBy', '==', elem)
})
postsCol.orderBy("sentAt", "desc").limit(5)

Upvotes: 0

Views: 721

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83058

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()).

Upvotes: 3

Related Questions