Mongoose: ignore parameter in query if it is null Mongoose: ignore parameter in query if it is null mongoose mongoose

Mongoose: ignore parameter in query if it is null


I just hit the same issue, if you are using ES6 supported node version, you should be able to use spread. it automatically takes care of the undefined

var filters = {     colour: "red",     size: undefined}Items.find({...filters}) // only colour is defined, so it becomesItems.find({colour:"red"})

NOTE if you are using Babel. you might need to define a object first.

var query = {...filters}Items.find(query)


You can unpack the variables in req.query using a 'destructuring assignment'.

const { color } = req.query;if(color) {   const items = await Items.find({ color })}

If you have multiple filters, you can use the variables from above. For example, you may have color and type parameters. With this, you can build up an object to pass to the find method.

const { color, type } = req.query;let query = {};if(color) {   query.color = color;}if(type) {   query.type = type;}const items = await Items.find(query);

If color or type is not in the original query, they will be undefined or falsy and so will skip the if statement for that parameter.Hope it works!


You may remove undefined keys from object before passing that object.

Object.keys(filter).forEach(key => filter[key] === undefined && delete filter[key])

Put the above code inside util and reuse it everywhere.