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)
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)
Share
Improve this question
asked Mar 28, 2017 at 9:33
MattMatt
6494 gold badges12 silver badges20 bronze badges
5
- where is the or in that? can you write pseudocode of what you want to achieve? which version of Mongoose do you use? – boroboris Commented Mar 28, 2017 at 9:36
- Well, @boroboris that is my question... how to do an OR in mongoose, I am using latest version of Mongoose – Matt Commented Mar 28, 2017 at 9:39
- I wanted to ask about the specific or conditions you want to use. – boroboris Commented Mar 28, 2017 at 9:49
- Oh sorry, I tried to pass an options inside the WHERE in this format '_id', 'username' – Matt Commented Mar 28, 2017 at 9:51
- I've found the part of the answer here: stackoverflow./questions/7382207/… so you can check that out too – boroboris Commented Mar 28, 2017 at 9:55
2 Answers
Reset to default 12Try something along those lines:
User.findOne({
$or:[
{'condition_1':param}, {'condition_2':param}
]},
function(err,docs){
if(!err) res.send(docs);
}
});
My solution
// Needed to user ObjectID parison
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)