Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OR operator with query builder in mongoose.js

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)
like image 916
Matt Avatar asked Mar 28 '17 09:03

Matt


People also ask

What is $or in mongoose?

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.

What does find () return in 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.

What is query in mongoose?

The Mongoose Query class provides a chaining interface for finding, updating, and deleting documents.

Is mongoose A ORM?

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.


1 Answers

Try something along those lines:

User.findOne({
     $or:[ 
       {'condition_1':param}, {'condition_2':param} 
     ]},
     function(err,docs){
       if(!err) res.send(docs);
     }
  });
like image 74
boroboris Avatar answered Oct 10 '22 20:10

boroboris