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)
The or operator is the counterpart to the and operator and is essential knowledge when working with database queries. We'll specifically show you how to use within mongoose.
Return value The returned value could be an array of documents, a single document if it matches only one, or an empty array if no document is matched.
The Mongoose Query class provides a chaining interface for finding, updating, and deleting documents.
Mongoose is similar to an ORM (Object-Relational Mapper) you would use with a relational database. Both ODMs and ORMs can make your life easier with built-in structure and methods. The structure of an ODM or ORM will contain business logic that helps you organize data.
Try something along those lines:
User.findOne({
$or:[
{'condition_1':param}, {'condition_2':param}
]},
function(err,docs){
if(!err) res.send(docs);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With