Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 918
JesterWest Avatar asked Nov 28 '22 16:11

JesterWest


1 Answers

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 becomes
Items.find({colour:"red"})

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

var query = {...filters}
Items.find(query)
like image 121
devric Avatar answered Dec 16 '22 16:12

devric