最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - delete property doesn't work in node.js - Stack Overflow

programmeradmin2浏览0评论

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 below delete userResult.password? just to be sure that jwt.encode doesn't mutate userResult somehow. – Federkun Commented Aug 27, 2017 at 10:13
  • 1 User is sequelize model? – alexmac Commented Aug 27, 2017 at 11:24
 |  Show 3 more ments

1 Answer 1

Reset to default 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) {
   ...
 }
发布评论

评论列表(0)

  1. 暂无评论