0

Using NodeJS with Mongoose and MongoDB for my back-end.

I am trying to do this (example):

controller.getUsersSearchAll = function(req, res){
    let last = req.query.last;
    let min = req.query.minPrice;
    let max = req.query.maxPrice;
    if(last && min && max){
        User.find()
            .where('last_name').equals(last)
            .where('age').gte(min).lte(max)
            .exec(function(err, result){
            res.json(result);
        });
    }else if(last){
        User.find()
            .where('last_name').equals(last)
            .exec(function(err, result){
            res.json(result);
        });
    }    
};

It works but in this way, it is static. The problem is when I have 10 conditions or more I had to apply many if conditions.

How to convert it to a dynamic way? Is there a smart way?

Vasilis Greece
  • 861
  • 1
  • 18
  • 38

1 Answers1

1

Why not just store your base query in a var and then add to it?

var query = User.find().where('last_name').equals(last)

// editing to show adding multiple where conditons
if(condition_1){
  query = query.where('age').gte(10)
}
if (condition_2){
  query = query.where('age').gte(50)
}
if (condition_3){
  query = query.where('age').gte(100)
}//...etc for any other where clauses you need to add

//Then exec your query and do something with the data
query.exec(function(err, data){})
user2263572
  • 5,435
  • 5
  • 35
  • 57
  • That was an example. If I had 10 conditions that solution is not applied in my case. In addition there is a possibility to search only by age and not with last_name. – Vasilis Greece Nov 25 '18 at 13:40
  • 1
    If you have 10 conditions, you need to write the logic for each condition. There is no avoiding that. The point is to build the common part of the query statement and store it in a variable. Then you can add any condition that applies. – user2263572 Nov 25 '18 at 13:42
  • Can you edit your answer with for each condition? Because I don't know what you mean exactly. – Vasilis Greece Nov 25 '18 at 13:44
  • Answer updated. I'd also recommend checking out this answer to understand why this works. https://stackoverflow.com/questions/8300844/what-does-return-this-do-within-a-javascript-function. – user2263572 Nov 25 '18 at 13:47