1

I wonder why I can't delete password object, my console result shows the password is still there, I wonder why.

User.comparePassword(password, user.password , (err, result) => {
  if (result === true){
    User.getUserById(user._id, (err, userResult) => {
      delete userResult.password

      const secret = config.secret;
      const token = jwt.encode(userResult, secret);

      console.log(userResult)

      res.json({success: true, msg: {token}});
    });
  } else {
    res.json({success: false, msg: 'Error, Incorrect password!'});
  }
}
alexmac
  • 19,087
  • 7
  • 58
  • 69
Jenny Mok
  • 2,744
  • 9
  • 27
  • 58

1 Answers1

9

There are multiple solutions to your problem. You cannot delete property from Mongoose query, because you get some Mongoose wrapper. In order to manipulate object you need to transform it to JSON object. So there are three possible way that I can remember to do that:

1) Call toObject method mongoose object (userResult) like this:

 let user = userResult.toObject();
 delete user['password'];

2) Redefine toJson method of User model:

UserSchema.set('toJSON', {
        transform: function(doc, ret, options) {
            delete ret.password;
            return ret;
        }
});

3) Query can return object without specified field, so that you don't need to delete anything:

 User.findById(user._id, {password: 0}, function (err, userResult) {
   ...
 }
Ivan Vasiljevic
  • 5,478
  • 2
  • 30
  • 35