elvin
elvin

Reputation: 55

How to define condition as variable to find method in mongodb?

I want to use code to manipulate 'condition' as variable before passing into 'find' method (for MongoDB):

let condition;

if (cat) {
   condition = { $and: [{brand: brnd},
                        {category: cat} ] 
               }  
} else { 
   condition = {brand: brnd} 
}

productCol.find(condition);

But I am unable to get this to work. Can anyone help me how I can make it to work? Thank you

Upvotes: 0

Views: 44

Answers (1)

saketh
saketh

Reputation: 813

Can you be more specific about your code like how did u setup your connection and how are you trying to use the result and what errors are you getting when you are trying to run your code. Please try the below code.

    var FindQuery=function(cat){
    if (cat) {
    var condition = { $and: [{brand: brnd},
                    {category: cat} ] }  
    } else { 
    var condition = {brand: brnd} 
    }

    return productCol.find(condition);
    };
    FindQuery(condition)

Upvotes: 1

Related Questions