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!'});
  }
}
8
  • What is userResult? Maybe its frozen or sth like that? Aug 27, 2017 at 9:25
  • please check this, stackoverflow.com/questions/33239464/… Aug 27, 2017 at 9:41
  • @Jonasw is a user object, no it's not frozen.
    – Jenny Mok
    Aug 27, 2017 at 9:49
  • 1
    if that doesn't work, can you move console.log(userResult) right below delete userResult.password? just to be sure that jwt.encode doesn't mutate userResult somehow.
    – Federkun
    Aug 27, 2017 at 10:13
  • 1
    User is sequelize model?
    – alexmac
    Aug 27, 2017 at 11:24

1 Answer 1

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) {
   ...
 }
2
  • 1
    Wow thanks so much didn't know it has anything to do with mongoose.
    – Jenny Mok
    Aug 27, 2017 at 11:43
  • I am glad I could help you :) Aug 27, 2017 at 11:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.