2

Let's say I need to query Firestore against a collection of subjects that I receive in a promise:

const subjects: string[] = await getSubjects(); //response: ['Math', 'Science', 'History'];

Since I don't know how many subjects might be returned in the promise at any given time, how would I go about dynamically generating the chain below so I can properly query Firestore?

ref.where('subject[subjects[0].toLowerCase()]', '==' , true)
    .where('subject[subjects[1].toLowerCase()]', '==' , true)
    .where('subject[subjects[2].toLowerCase()]', '==' , true);

The more subjects that are returned, the more .where() methods it would need to generate.

katyusha
  • 151
  • 1
  • 11

1 Answers1

3

Creating a Query follows a builder pattern: when you call where it returns a Query and on that Query you can call where again.

So if you have an array of subjects and want to create a query of those, you can do:

var query = firebase.firestore().collection("bla");
['Math', 'Science', 'History'].forEach((subject) => {
   query = query.where(`subject[${subject}.toLowerCase()]'`, '==' , true);
})
query.get()....

Note that Firestore nowadays supports an array-contains-any operator, which scale significantly better for these types of operations and can deal with up to 10 subjects at once.

To use this you documents will need to contain an array subjects, like:

subjects: ['Math', 'Biology']

And then you'd query it with:

var query = firebase.firestore().collection("bla")
  .where('subjects', 'array-contains-any', ['Math', 'Science', 'History']);
query.get()...
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807