motionless570
motionless570

Reputation: 929

Is there a way to filter multiple fields in Firebase Firestore in Reactjs

I am trying to have multiple inequality filters on multiple fields in my Firebase Firestore collection to be able to search for certain properties on certain criteria, but Firebase Firestore doesn't allow this for no obvious or acceptable reason. What I want to know is if there is a way to achieve what I am trying to do but with a different methodology.

for example i want to filter my properties based on price and number of bed rooms so i would write something like .where("price",">=",price).where("bedrooms",">="bedrooms)

But of course, Firebase and its unlimited limitations don't allow us to do something as simple as this. So, is there a way I can overcome this?

Here is my code:

 const search = () => {

    firebase
      .firestore()
      .collection("Properties")
      .where("location", "==", address)
      .where("bedrooms", "==", rooms)
      .where("category", "==", category)
      .where("price", ">=", price)
      .where("type","==", type)
      .get()
      .then((result) => {
        if (result.size == 0) {
          // Toast.fire({
          //   icon: "error",
          //   title: "No properties were found, please modify your search",
          // });
        } else {
            setPropertyCount(result.size);
            const properties = result.docs.map((doc) => doc.data());
            setSearchData(properties);
        }
      });
  };

Upvotes: 0

Views: 979

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138824

Yes, the following query will not work:

.where("price",">=",price).where("bedrooms",">="bedrooms)

Because of the limitation that is mentioned in the documentation:

In a compound query, range (<, <=, >, >=) and not equals (!=, not-in) comparisons must all filter on the same field.

So if you try to perform this query, you'll get an error message that sounds like this:

All where filters with an inequality (notEqualTo, notIn, lessThan, lessThanOrEqualTo, greaterThan, or greaterThanOrEqualTo) must be on the same field. But you have filters on 'price' and 'bedrooms'

But that is happening not to upset you, but to guarantee performance. In order to massively scale, there are some limitations that we should take into consideration.

So, is there a way I can overcome this?

Yes, there is. There is a technique called denormalization. So I recommend you check my answer from the following post:

So if you're new to NoSQL databases, that might sound some kind of weird, but it will help us solve this kind of problem. So in your case, I would create a collection for each type of apartment (one bedroom, two bedrooms, etc.) and I would query like this:

firebase
    .firestore()
    .collection("twoBedrooms")
    .where("price",">=",price)

Case in which there are no limitations. If you need more such filters, please also don't forget to create an index.

Upvotes: 2

Related Questions