Querying optional string in mongoose 4.0

41 views Asked by At

I have a field named Category which i want to query. I am using

Deal.find({Category:categoryName},function(err, doc){
...
}

This works fine when giving a value for categoryName. I want to return all the entries of the database if categoryName is empty.

i.e

If categoryName is given
     then return specific entries
Else if categoryName is empty 
     then return all entries

I can use if else statement to write 2 different queries but I have 4 more fields like Category and i have to do similar query for all the 4 fields. i.e. a total of 16 if else statements.

What is the best method to do this type of query?

1

There are 1 answers

0
chridam On

Create a query object based on those conditionals prior to assigning it as the find() argument:

var query = {};
if (categotyName !== undefined || categoryName !== "") query["Category"] = categoryName;

Deal.find(query, function(err, doc){
    ...
}