The following code works with no querystrings or one querystring only. In other words, simply going to /characters returns all characters. But if you were to specify a querystring parameter /characters?gender=male it will return only male characters.
How could I extend this to work with either 1, 2, 3, or no querystrings? I would really prefer to avoid writing 8 or 9 different if-statements for each case. I was hoping Mongoose would simply ignore a $where clause if it's null or undefined, but that is not the case (see commented out code).
var gender = req.query.gender;
var race = req.query.race;
var bloodline = req.query.bloodline;
var query = Character.find();
if (gender)
query = query.where('gender').equals(gender);
if (race)
query = query.where('race').equals(race);
if (bloodline)
query = query.where('bloodline').equals(bloodline);
/*
query
.where('gender').equals(new RegExp('^' + gender + '$', 'i'))
.where('race').equals(new RegExp('^' + race + '$', 'i'))
.where('bloodline').equals(new RegExp('^' + bloodline + '$', 'i'));
*/
query.exec(function(err, characters) {
if (err) throw err;
res.send(characters);
});
Edit: Well I guess I could do it with 7 if-statements for now. Unless someone finds a more elegant solution.
Edit 2:
Thanks guys. It's difficult to pick one answer because both of you have helped me to achieve this concise solution. Here is the entire thing now.
var conditions = {};
for (var key in req.query) {
if (req.query.hasOwnProperty(key)) {
conditions[key] = new RegExp('^' + req.query[key] + '$', 'i');
}
}
var query = Character.find(conditions);
query.exec(function(err, characters) {
if (err) throw err;
res.send({ characters: characters });
});