Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore undefined values that are passed in the query object parameter for Mongoose's Find function?

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.


2 Answers

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.

like image 135
Volodymyr Avatar answered Oct 22 '25 15:10

Volodymyr


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
}))
like image 34
Zuum Dj Avatar answered Oct 22 '25 17:10

Zuum Dj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!