20

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=req.body.lastName,
    companyName=req.body.companyName,
    email=req.body.email;
});

I'd like to build a query up from these values, but if the field has no value, I obviously don't want to include it in the search (searching for "" would change the results)

I've tried a couple different things, like building a string to place in:

mongoose.model('customers').find({QUERY STRING WOULD GO HERE} ,function(err, data) {
    if (err) return console.error(err);
    console.log(data);
});

But that doesn't seem to work properly. I also tried "stacking" search queries like this:

if(firstName !="") {
    mongoose.model('customers').find({firstName: firstName})
}

and then executing the search like this:

mongoose.model('customers').exec(function(err, customer){
    console.log(customer);
});

But that causes 500 errors (and I'm not sure if there's any more info I can get from them).

Please help a Newbie dynamically build a mongoose search query :(

2
  • Instead of a query string, have you tried constructing a query object? (if you're new to javascript other languages call it "hash" or "map" or "array") Commented Apr 6, 2015 at 6:27
  • @slebetman You're absolutely right. I looked up how to create an object, but just wasn't doing it properly :( Commented Apr 6, 2015 at 20:27

3 Answers 3

38

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
});
Sign up to request clarification or add additional context in comments.

3 Comments

I did exactly this and it worked! I was trying to make an object wrong the whole time! Thanks for helping me out!
Hi DemoUser, If I want to put the 'in' checking how to use the above one, means I want check this {usernames: {$in:['x','y','z']}} . In this case what is first variable and second variable.
@RamBen - you can use: query["usernames"] = {$in:['x','y','z']}}
13

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
});

2 Comments

Thanks for the input! My usecase is a lot simpler than that, but I appreciate it either way! I'm sure someone will get good use of it!
Before using $where make sure you consider these points,mongodb.com/docs/manual/reference/operator/query/where
10

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

})

1 Comment

This is pretty helpful, thanks! I've done this in a couple other places in my app and it's been pretty helpful!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.