0

I have a firebase database of "users" with bunch of fields. I also have a filter that executes a query on those fields and returns the filtered users. The problem is the query can get an object where the location value is an empty string, if the value is "" I want ignore that .where line of code but execute the other ones. I've tried converting the value to undefined and null but undefined throws an error and null displays no users.

exports.filterUsers = (req, res) => {    
 db.collection("users")
.where("gender", "==", req.body.gender)
.where("age", "<=", req.body.maxAge)
.where("age", ">=", req.body.minAge)
.where("location", "==", req.body.location)
.get()
Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
glaze
  • 1,309
  • 2
  • 6
  • 6

1 Answers1

3

Since the where() method returns a Query, you can do as follows:

let query = db.collection("users")
.where("gender", "==", req.body.gender)
.where("age", "<=", req.body.maxAge)
.where("age", ">=", req.body.minAge);

if (req.body.location === "") {
   query = query.where("location", "==", req.body.location);
}

query.get()...
Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121