Jen*_*Mok 1 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!'});
}
}
Run Code Online (Sandbox Code Playgroud)
您的问题有多种解决方案。你不能从 Mongoose 查询中删除属性,因为你得到了一些 Mongoose 包装器。为了操作对象,您需要将其转换为 JSON 对象。所以我记得有三种可能的方式来做到这一点:
1)像这样调用toObject方法 mongoose 对象 ( userResult):
let user = userResult.toObject();
delete user['password'];
Run Code Online (Sandbox Code Playgroud)
2)重新定义模型toJson方法User:
UserSchema.set('toJSON', {
transform: function(doc, ret, options) {
delete ret.password;
return ret;
}
});
Run Code Online (Sandbox Code Playgroud)
3)查询可以返回没有指定字段的对象,这样你就不需要删除任何东西:
User.findById(user._id, {password: 0}, function (err, userResult) {
...
}
Run Code Online (Sandbox Code Playgroud)