So:
Sound.find({
what: req.query.what,
where: req.query.where,
date: req.query.date,
hour: req.query.hour}, function(err, varToStoreResult, count) {
//stuff
});
Say that only req.query.what has an actual value, "yes" for example, while the rest (req.query.where, req.query.date, etc.) are all undefined/empty. If I leave this code as is, it would look for docs which have what = req.query.what AND where = req.query.where, etc. but I would only want it to find docs which have their what value = to req.query.what, since the other fields are undefined/empty.
You have to filter your res.query
object from undefined/empty values first, and then pass it to find
function. If you have just a couple of properties, you can use if
statement:
const query = req.query;
const conditions = {};
if (query.what) {
conditions.what = query.what;
}
if (query.where) {
conditions.where = query.where;
}
....
Sound.find(conditions, function () {});
Or if there is a lot of properties you can iterate over them:
const query = req.query;
const conditions = Object.keys(query)
.reduce((result, key) => {
if (query[key]) {
result[key] = query[key];
}
return result;
}, {});
Sound.find(conditions, function () {});
Also, I would not advise to remove properties from the actual res.query
object - delete res.query.what
- because you won't be able to use it in another middleware if you would like to.
May be a bit ugly, but works for me for filtering undefines. Just perform JSON.parse(JSON.stringify()) on your query like this:
JSON.parse(JSON.stringify({
what: req.query.what,
where: req.query.where,
date: req.query.date,
hour: req.query.hour
}))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With