Programmatically build dynamic query with Mongoose

前端 未结 3 1169
余生分开走
余生分开走 2020-12-24 14:44

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         


        
相关标签:
3条回答
  • 2020-12-24 15:26

    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
    });
    
    0 讨论(0)
  • 2020-12-24 15:31

    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){
    
    })
    
    0 讨论(0)
  • 2020-12-24 15: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
    });
    
    0 讨论(0)
提交回复
热议问题