mjabraham mjabraham - 1 year ago 90
Node.js Question

Mongoose & MongoDB: Retrieve results narrowed by multiple parameters

I need to get data from MongoDB that is first narrowed by one initial category, say '{clothing : pants}' and then a subsequent search for pants of a specific size, using an array like sizes = ['s','lg','6', '12'].

I need to return all of the results where 'pants' matches those 'sizes'.

I've started a search with:

Product.find({$and:[{categories:req.body.category, size:{$in:req.body.sizes}}]},
function(err, products) {
if (err) { console.log(err); }
return res.send(products)

I really don't know where to go from there. I've been all over the Mongoose docs.

Some direction would be very helpful.

Answer Source

The mongoose queries can receive object like Mongodb would. So you can pass the search parameters separated by ,

Product.find({categories:req.body.category, size:{$in:['s','lg','6', '12']}})

For more information on $in, check here

For more information on $and operator, check here (note we can ommit the $and operator in some cases and that is what I did)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download