Search code examples
node.jsmongodbrestexpressmongoose

Mongoose: ignore parameter in query if it is null


I have a simple REST API and I would like to implement filtering on a specific endpoint.

Imagine I have an endpoint like this:

localhost:5000/api/items?color="red"

Which handles request like this:

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

This works when the color parameter is present. However, if the color parameter is omitted then the query searches for items where the color is undefined. This is not the behaviour I need.

In my case, I would like to add multiple filter parameters which are ignored if they are not present. Do I have to create a separate query for each case or is there an option to tell Mongoose not to search for a field (in this case color) if it is null or undefined?


Solution

  • 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!