1

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?

Ripas55
  • 423
  • 1
  • 6
  • 20

1 Answers1

0

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.

  • so what you're saying, in the cloud function I need to do 1 query on calorie results, get ALL documents, then filter those document hits with javascript and return result to the client? – Ripas55 Jul 01 '22 at 17:41
  • Check the [answer provided](https://stackoverflow.com/questions/50658651/firestore-multiple-range-query) by Frank van Puffelen, he posted a few ways this can be done – Andres Fiesco Casasola Jul 01 '22 at 17:49
  • Yes, that workaround should work. It's a bit time consuming since you will filter the properties manually, but should do the work – Andres Fiesco Casasola Aug 05 '22 at 20:14