I am trying to get data from my mongoDB database by using mongoose filters. The scenario is that each user object in the database has certain fields like “Region” or “Sector”.
Currently I am getting all the users that contain the keyword “region” in there object like so:
// Filter all healthcare bios by region app.get('/user',function(req, res) { // use mongoose to get all users in the database User.find({region: "NA"}, function(err, user) { // if there is an error retrieving, send the error. nothing after res.send(err) will execute if (err) { res.send(err); } // return all todos in JSON format console.log(user); res.json(user); }); });
How can put some conditions in mongoose that it return users that contain both “region” && “Sector” in their objects. Currently its only returning the user which have the region keyword in them.
I have tried using $and operator but I couldn’t get it to work.
Advertisement
Answer
app.get('/user',function(req, res) { User.find({region: "NA",sector:"Some Sector"}, function(err, user) { if (err) { res.send(err); } console.log(user); res.json(user); }); });
If you want data with either region:”NA” or sector:”Some Sector”. you can use $or
operator.
User.find({$or:[{region: "NA"},{sector:"Some Sector"}]}, function(err, user) { if (err) { res.send(err); } console.log(user); res.json(user); });