Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose where query with "or"

How would I do this in mongoose, I could not find anything with an "or"

userModel.where('email')
         .equals(req.body.email)
         .or('username').equals(req.body.username) //need the "or"
         .exec(function (err, docs) {

  ....

  });
like image 815
Michael W Riemer Jr Avatar asked Nov 24 '15 15:11

Michael W Riemer Jr


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?

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 __ V in MongoDB?

The __v field is called the version key. It describes the internal revision of a document. This __v field is used to track the revisions of a document. By default, its value is zero ( __v:0 ).

How do I use $in in MongoDB?

For comparison of different BSON type values, see the specified BSON comparison order. If the field holds an array, then the $in operator selects the documents whose field holds an array that contains at least one element that matches a value in the specified array (for example, <value1> , <value2> , and so on).


1 Answers

I believe you might want to have a find query like so:

userModel.find({$or: [{email: req.body.email}, {username: req.body.username}]})
    .exec(function (err, docs) {
    ...
});

docs will then contain all documents in the userModel collection whose email field equals the one specified in the request body OR whose username field equals the one specified in the request body.

like image 139
Florian Avatar answered Oct 12 '22 01:10

Florian