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?
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)
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