I\'m trying to build a search from input received from a form.
router.get(\'/data\', function(req, res) {
var firstName=req.body.firstName,
lastName
For people using newer JavaScript (and especially on Node.js 7.6.0+ or Babel).
The best way I found for programmatically building queries (based on if
clauses etc.) is using the Query and the alternative syntax.
let query = PersonModel().find();
if (isMale) {
query.where('sex', 'male');
} else {
query.where('sex', 'female');
}
query.where('alive', true);
// and then to run the query
const result = await query.exec();
Note the async/await
usage here. It's working perfectly on Node.js 7.6.0+. If you don't want to use async/await
you can just use Promises like so:
query.exec().then(result => {
// result has your... results
});
To avoid checking each parameter independently you can loop through them.
var query = {};
for(var key in req.body){ //could also be req.query and req.params
req.body[key] !== "" ? query[key] = req.body[key] : null;
}
mongoose.model('customers').find(query, function(err, customers){
})
try creating query
object, like:
//generate query object based on availability of value
var query = {};
if( your_variable !== "" ) {
query["some_key"] = your_variable;
}
if( your_second_variable !== "" ) {
query["some_other_key"] = your_second_variable;
}
mongoose.model('customers').find(query, function(err, c) {
//do something
});