删除属性不在node.js中工作

时间:2017-08-27 09:12:49

标签: javascript node.js express ecmascript-6

我想知道为什么我无法删除密码对象,我的控制台结果显示密码仍然存在,我想知道为什么。

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!'});
  }
}

1 个答案:

答案 0 :(得分:2)

您的问题有多种解决方案。您无法从Mongoose查询中删除属性,因为您获得了一些Mongoose包装器。为了操作对象,您需要将其转换为JSON对象。因此,有三种可能的方法让我记得这样做:

1)像这样调用toObject方法猫鼬对象(userResult):

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

2)重新定义toJson模型的User方法:

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

3)查询可以返回没有指定字段的对象,因此您不需要删除任何内容:

 User.findById(user._id, {password: 0}, function (err, userResult) {
   ...
 }