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?

1 Answer 1

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

4 Comments

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.
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.
Can you edit your answer with for each condition? Because I don't know what you mean exactly.
Answer updated. I'd also recommend checking out this answer to understand why this works. stackoverflow.com/questions/8300844/….

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.