How can I get firestore document filtered on multiple fields?

Viewed 58

I have firestore recipe collection and my goal is to get a first document that matches this criteria:

kcal<800
carbs<100
fats<50
protein>60

I have just read firebase documentation and it seems that I can't perform a query that has range filters on multiple fields:

// this is invalid
const q = query(citiesRef, where("state", ">=", "CA"), where("population", ">", 100000));

Now I am being left in the dark, what do I do now, what are my options to achieve my aforementioned goal?

1 Answers

According to Google’s Firebase documentation, in compound queries, you can only perform range filters on one field only:

const q1 = citiesRef.where("state", ">=", "CA").where("state", "<=", "IN");
const q2 = citiesRef.where("state", "==", "CA").where("population", ">", 1000000);

And, range filters on different fields are not allowed:

citiesRef.where("state", ">=", "CA").where("population", ">", 100000); (not allowed)

As a work around, you can create a cloud function where you can filter all the properties needed manually. Then, you can create a query in a range and then filter the documents with the other desired properties.

Related