Mongoose optional search query parameters?

前端 未结 3 1867
时光说笑
时光说笑 2020-11-28 15:56

I have a following situation. I need to build a mongoose query, based on certain arguments if present.

I.e. if object like this is passed

{
    playe         


        
相关标签:
3条回答
  • 2020-11-28 16:28

    In case someone encounters same question, here's how I solved it:

    var query = {
        player: 'player'
    };
    
    Entry.find({
        player: query.player,
        action: (query.action) ? query.action:/.*/
    }).
        exec(function(err, res){
            console.log(res);
        });
    
    0 讨论(0)
  • 2020-11-28 16:31

    With ES6, you can do this with a splat & ternary like this:

    Entry.find({
      player: obj.player,
      ...obj.action ? { action: obj.action } : {}
    })
    .exec(function(err, res){
        console.log(res);
    });
    
    0 讨论(0)
  • 2020-11-28 16:34

    Build up your query object programmatically:

    var query = {
        player: 'player'
    };
    
    if (obj.action) {
        query.action = obj.action;
    }
    
    Entry.find(query).exec(function(err, res){
        console.log(res);
    });
    
    0 讨论(0)
提交回复
热议问题