Ying Yangz
Ying Yangz

Reputation: 177

Check if an item exists in different fields

How do I check if an item exists in different fields in a document?

I currently have the below :

Room.findOne({
  editUrl: req.params.roomName
}, function(err, room) {
  if (err) {
    return err;
  }
 }

I want to also check if req.params.roomName exists in the field viewUrl. What is the way to do this without having to do another findOne().

EDIT : using the $or operator I can check if an item is in field 1 or field 2. What I need now is how do I add a condition if the item i am searching for is in field 1 and another condition if it is in field 2

EDIT 2: Please find below my original function: What this was doing is first check if the parameter exist. If it exists then update that document and add the user in the users array. Now what I need is to check if the parameter exists in either the editUrl field or in the viewUrl field. If it exists in the editUrl field then add the user to the users array else if it exists in the viewUrl field, then add the user to the viewOnlyUsers array.

Room.findOne({
  editUrl: req.params.roomName
}, function(err, room) {
   if (err) {
     return err;
   }
   if (room != null) {
     Room.update({
       editUrl: req.params.roomName
   }, {
     $addToSet: {
       users: req.user._id
  }
   }, function(err,
  count) {
  if (!count) {
    return err
  }
});
res.render('account/board');
} else {
res.sendStatus(404);
}
});

Upvotes: 0

Views: 93

Answers (1)

Nishant
Nishant

Reputation: 3694

You just have to use the $or operator

Room.findOne({
$or:[{editUrl: req.params.roomName},{viewUrl: req.params.roomName}]
}, function(err, room) {
  if (err) {
    return err;
  }
 }

Documentation of $or operator https://docs.mongodb.org/manual/reference/operator/query/or/

Upvotes: 1

Related Questions