aman verma
aman verma

Reputation: 762

Mongoose query to return an array which does not contains a specific field?

How to write a query in Mongoose where I want to search in array and if a value is not present then I want to update my document. I have read many StackOverflow answers, but none specify how to use it with array operations. My query is given below, too. Can someone please tell me how to do this I have been stuck here for awhile. In the code below, I am trying to find inside reg_ids array if none of its value contains reg_id which is a string then I want to update my document

userregidsmodel.findOneAndUpdate(
  {email_id: jeeb_no, reg_ids: { $ne: reg_id } }, 
  {$push: {reg_ids: reg_id} }, 
  {'total_follow_notifications': 1, 'total_notifications': 1, '_id':0},
  function(err, docs) {
    if (err) {
      console.log('Error Finding query results');

      console.log(err);
      res.json({success: 0, message : err});
      return next(err);
    } else {
      if (docs) {
        console.log('Login Successfull');
        res.json({success : 1, message : "Login Successfull", mobile_no: mobile_no, email_id: email_id});
        return next();
      } else {
        console.log('login Successfull app previous token is used');
        res.json({success : 1, message : "Login Successfull", mobile_no: mobile_no, email_id: email_id});
        return next();
      }
    }
  });

Upvotes: 0

Views: 654

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311835

The third parameter to findOneAndUpdate is an options parameter, not just a field selection parameter, so you need to wrap your field selection object in a {select: ...} object:

userregidsmodel.findOneAndUpdate(
  {email_id: jeeb_no, reg_ids: { $ne: reg_id } }, 
  {$push: {reg_ids: reg_id} }, 
  {select: {'total_follow_notifications': 1, 'total_notifications': 1, '_id':0}},
  function(err, docs) { ...

Upvotes: 1

Related Questions