Vasilis Greece
Vasilis Greece

Reputation: 907

Mongoose/MongoDB dynamic where depend URL Parameters

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?

Upvotes: 0

Views: 207

Answers (1)

user2263572
user2263572

Reputation: 5606

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

Upvotes: 1

Related Questions