我正在使用MEAN.js开展一些项目,遇到了以下问题。我想要计算一些用户的个人资料并将其保存到数据库中。但是在用户模型中的方法存在问题:
UserSchema.pre('save', function(next) {
if (this.password && this.password.length > 6) {
this.salt = new Buffer(crypto.randomBytes(16).toString('base64'), 'base64');
this.password = this.hashPassword(this.password);
}
next();
});
如果我在修改时发送密码,它将更改凭据,因此用户下次无法登录。我想在保存之前从用户对象中删除密码,但我不能这样做(请看下面我的代码注释):exports.signin = function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err || !user) {
res.status(400).send(info);
} else {
/* Some calculations and user's object changes */
req.login(user, function(err) {
if(err) {
res.status(400).send(err);
} else {
console.log(delete user.password); // returns true
console.log(user.password); // still returns password :(
//user.save();
//res.json(user);
}
});
}
})(req, res, next);
};
出了什么问题?为什么删除方法返回 true,但是没有任何反应?感谢您的帮助 :)
password
属性是否确实是user
对象的属性,而不是来自原型链上的某个对象(hasOwnProperty)吗?将其设置为undefined
是不够的(抱歉,我对 MEAN 栈没有经验)。就 JSON 编码而言,结果应该没有任何区别。 - Prusse