Krishna Kumar
Krishna Kumar

Reputation: 2121

MongoDB : how to put conditional for multiple optional value

How to apply multi condition in mongoDB find condition with same key name??

I have collection in MongoDB:

[{
    'name': 'test1',
    'brand': 'A'
}, {
    'name': 'test2',
    'brand': 'B'
}, {
    'name': 'test3',
    'brand': 'C'
}, {
    'name': 'test4',
    'brand': 'D'
}]

server.js

app.get('/products', function(request, response) {
    // request.query => {'brand': 'A', 'brand: 'B', 'brand': 'C'}
    mongoose.model('products').find(request.query, function(err, data) {
        response.json(data);
        // data shoule be matching only if 'brand': 'A' or 'brand': 'B' or brand: 'C'
    });
});

Thanks in advance :)

Upvotes: 0

Views: 755

Answers (1)

laggingreflex
laggingreflex

Reputation: 34627

You'll need to create the query object using $or operator, like this:

var query = { $or: [] };
for (key in req.query)
    query.$or.push({ key: request.query[key] });
//=> { $or: [ {brand: 'A'}, {brand: 'B'},  …] }

Then use that as your query

Model.find(query, function(err, data){
    res.json(data);
});

Upvotes: 3

Related Questions