Russell C.
Russell C.

Reputation: 608

How to make an 'OR' condition mongo node

Is this how you make an or condition in mongo and node?

var conditions = {
$or:[
        {
            username: req.body.globalUserName,
            'pendingFriends._id': {$ne: req.user._id.toString()}
        },
        {
            username: req.body.globalUserName,
            'friends._id': {$ne: req.user._id.toString()}
        }
    ]
}

Upvotes: 1

Views: 831

Answers (2)

Rowland
Rowland

Reputation: 1823

$or in MongoDB performs a logical OR on an array of expressions/conditions. see docs

Since username: req.body.globalUserName is a common denominator in your conditionals if I got you correctly, you might need $and operator also.

var conditions = {
 $and: [ 
         { username: req.body.globalUserName },
         $or: [
                 {'pendingFriends._id': {$ne: req.user._id.toString()},
                 {'friends._id': {$ne: req.user._id.toString()}}
              ]
        ]
}

Upvotes: 1

RONAK SUTARIYA
RONAK SUTARIYA

Reputation: 544

-> The $or operator performs a logical OR operation on an array of two or more <expressions> and selects the documents that satisfy at least one of the <expressions>

-> syntax =

{ $or: [ { <expression1> }, { <expression2> }, ... , { <expressionN> } ] }

var conditions = {
 $and: [ 
         { username: req.body.globalUserName },
         $or: [
                 {'pendingFriends._id': {$ne: req.user._id.toString()},
                 {'friends._id': {$ne: req.user._id.toString()}}
              ]
        ]
}

please refer to Documentation of or in mongo

Upvotes: 0

Related Questions