Firestore query with empty string , 'any' or 'all'

Viewed 304

I have filter on my website, I need to retrieve data based on the inputs in the filter. Some fields of the filter can be empty (''), I want to be able to ignore those queries related to those fields basically. Something like this

//fields
const { country, age, gender, contract, budget_low, budget_high } = queries;

//query
db.collection("users")
        .where("country", "in", country === "" ? "any" : "Nigeria")
        .where("gender", "in", gender === "" ? "any" : "Male")
        .where("age", "in", age === "" ? "any" : "21")
        .get()
        .then((querySnapshot) => {
          var data = [];
          querySnapshot.forEach((doc) => {
            data.push(doc.data());
          });
          setPeers(data);
        })
        .catch((error) => {
          console.log("Error getting documents: ", error);
        });

Is there a way to use 'any' or 'all' if the fields is empty (''), so that way I retrieve all data conditionally (if filter field exists)?

1 Answers

You'll want to dynamically create your query, and only add the conditions for the values that the user actually selected.

let query = db.collection("users");

if (country !== "") query = query.where("country", "==", country);
if (gender !== "") query = query.where("gender", "==", gender);
if (age !== "") query = query.where("age", "==", age);

query.get()...

In the new modular/v9 syntax, that'd be:

let conditions = []

if (country !== "") conditions.push(where("country", "==", country));
if (gender !== "") conditions.push(where("gender", "==", gender));
if (age !== "") conditions.push(where("age", "==", age));

let query = query(collection(db, "users"), ...conditions);

getDocuments(query)...
Related