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? Commented Aug 27, 2017 at 9:25
  • please check this, stackoverflow.com/questions/33239464/… Commented Aug 27, 2017 at 9:41
  • @Jonasw is a user object, no it's not frozen. Commented 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. Commented Aug 27, 2017 at 10:13
  • 1
    User is sequelize model? Commented 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) {
   ...
 }
Sign up to request clarification or add additional context in comments.

2 Comments

Wow thanks so much didn't know it has anything to do with mongoose.
I am glad I could help you :)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.