How to build a conditional query in Mongoose?
I am using destructing of objects for this task.
const filter = req.query.filter ? { _id: { $in: req.query.filter.split(',') } } : {};
const category = req.query.category ? { category: req.query.category } : {};
// more variables that you need and are empty objects if don't exist
const all = await Post.find({ ...filter, ...category }).exec();
You don't need to call Query#where
repeatedly, since you can pass all the conditions to Mongoose Model#find as:
var filteredQuery = {},
acceptableFields = ['gender', 'race', /* etc */ ];
acceptableFields.forEach(function(field) {
req.query[field] && filteredQuery[field] = req.query[field];
});
var query = Character.find(filteredQuery);
You'll also want to sanitize req.query
depending on the allowed parameters you have in mind.
Well,
I would recommend something like this:
var query = Character.find()
if(req.params.length < 0) {
for(var key in req.params) {
query.where(req.params[key]).equals(key);
}
} else {
// do something without query params
}
this is not tested by me but it should work (maybe you need to modify it a bit but you get the idea). This solution is all about not checking what actually is in the params so be sure only good stuff comes in or validate it somewhere in the for loop, but would require some regex or if statements.
Hope this helps you.