0

This is my user schema

 var UserSchema = new Schema({
        Pcard: [{ type: Schema.Types.ObjectId, ref: 'Pcard'  }]
})

These are id's saved in user Pcard array

  "user": { // id 59560bc83e1fdc2cb8e73236
     "Pcard": [
                "595b43d16e4b7305e5b40845",
                "595b459a6e4b7305e5b40848",
                "595f48f58117c85e041f1e1c",
            ],
}

This is my Pcard Scema

var PcardSchema = new Schema({
    Time : {
        type : Date,
        default: Date.now
    },

})

I want to find user having Id and which also contains some id in Pcard array

User.find({  _id: req.user._id,
                       Pcard:{$in : [req.params.PcardId] }
                    }, function (err, Userpresent) {
                         if (err) {
                                res.json(code.Parked);
                           }
                          if (Userpresent === null || Userpresent === undefined) {

                     res.json(code.notAllowed);
                         }else{

This else is execting everytime.



}                        
    }
                    });

when i querying with user which does not have a Pcardid in Pcard array it is still going in else condition ! for eg . i am querying with this id 59560bc83e1fdc2cb8e73236 and this not contain 5957bd177e996b56d08b991a in Pcard array but still it is going on else part of the user query.

  • Possible duplicate of [MongoDB find with id and id in array using $in operator](https://stackoverflow.com/questions/45007161/mongodb-find-with-id-and-id-in-array-using-in-operator) – Thomas Bormans Jul 10 '17 at 09:51
  • not working either –  Jul 10 '17 at 10:09
  • You are saying it always finds a user ? even if the PcardId is not present in the Pcard array ? – Rohail Najam Jul 10 '17 at 10:20
  • @RohailNajam Yes , i want to find the user if both these conditions matches –  Jul 10 '17 at 10:21
  • It most likely won't matter, but you don't need to use `$in`, just use `{ _id : req.user._id, Pcard : req.params.PcardId }` – robertklep Jul 10 '17 at 13:45

1 Answers1

0

If you are expecting only one user, use findOne.

Might be useful/cleaner for you to return early instead of having a bunch if-else.

User.findOne({  
    _id: req.user._id,
    Pcard: { $in : [req.params.PcardId] }
}, function (err, user) {
    if (err) {
        return res.json(code.Parked);
    }
    // simplified: undefined and null are both falseys
    if (!user) {
        return res.json(code.notAllowed);
    }

    // user should be found at this point

});

Good read: All falsey values in JavaScript

Mikey
  • 6,728
  • 4
  • 22
  • 45
  • Thanks , But it is not working with just using Find ? –  Jul 13 '17 at 18:52
  • If you use `find`, it should be `user[0]` that you should be working with. But remember `find` is more expensive than `findOne` as you are looking for many results opposed to just one. – Mikey Jul 13 '17 at 18:53