I wonder why I can't delete password object, my console result shows the password is still there, I wonder why.
UserparePassword(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!'});
}
}
I wonder why I can't delete password object, my console result shows the password is still there, I wonder why.
User.parePassword(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!'});
}
}
Share
Improve this question
edited Aug 27, 2017 at 11:23
alexmac
19.6k7 gold badges64 silver badges74 bronze badges
asked Aug 27, 2017 at 9:12
Jenny MokJenny Mok
2,8049 gold badges33 silver badges62 bronze badges
8
- What is userResult? Maybe its frozen or sth like that? – Jonas Wilms Commented Aug 27, 2017 at 9:25
- please check this, stackoverflow./questions/33239464/… – Raghav Garg Commented Aug 27, 2017 at 9:41
- @Jonasw is a user object, no it's not frozen. – Jenny Mok Commented Aug 27, 2017 at 9:49
-
1
if that doesn't work, can you move
console.log(userResult)
right belowdelete userResult.password
? just to be sure thatjwt.encode
doesn't mutateuserResult
somehow. – Federkun Commented Aug 27, 2017 at 10:13 -
1
User
is sequelize model? – alexmac Commented Aug 27, 2017 at 11:24
1 Answer
Reset to default 9There 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) {
...
}