Reputation: 649
How do I do an 'OR' operator with query builder in Mongoose?
I tried something like this: Find a user by ID or Username but it didn't work.
User.findOne({})
.where( '_id', 'username').equals(param)
Upvotes: 6
Views: 10356
Reputation: 649
My solution
// Needed to user ObjectID comparison
const { ObjectID } = require('mongodb');
// Check if param is a valid ID otherwise is Username
let id_or_username = ObjectID.isValid(id) ? '_id' : 'username';
// Find post by ID or Username
Home
.findOne({})
.where(id_or_shortid).equals(id)
.exec(callback)
Upvotes: 0
Reputation: 1620
Try something along those lines:
User.findOne({
$or:[
{'condition_1':param}, {'condition_2':param}
]},
function(err,docs){
if(!err) res.send(docs);
}
});
Upvotes: 12