Javascript node js-在mongoose pre(';save';…)中散列pwd不会';t存储到数据库
当我使用mongoose.pre('save'…)散列我的pwd时,它可以工作,但是数据库中实际存储的值不是散列值。为什么会重置?谢谢Javascript node js-在mongoose pre(';save';…)中散列pwd不会';t存储到数据库,javascript,node.js,mongodb,hash,Javascript,Node.js,Mongodb,Hash,当我使用mongoose.pre('save'…)散列我的pwd时,它可以工作,但是数据库中实际存储的值不是散列值。为什么会重置?谢谢 user.password = 'abcd'; UserSchema.pre('save', function(next){ if (!this.isModified('password')) return next(); console.log('this.password: ' + this.password); // returns a
user.password = 'abcd';
UserSchema.pre('save', function(next){
if (!this.isModified('password')) return next();
console.log('this.password: ' + this.password); // returns abcd
bcrypt.hash(this.password, secret.pwdHashSecret, null, function(err, hash) {
if(err)
return next(err);
this.password = hash;
console.log('this.password: ' + this.password); // returns hashed pwd
next();
});
});
user.save(function(err) {
console.log('user.password: ' + user.password); // returns abcd???
}
每个函数都有自己的
值。您正在将password
属性添加到bcrypt.hash
回调函数的this
值中。您应该修改外部函数的此
值的密码
属性。一个选项是存储外部函数的这个值并在回调中使用它:
UserSchema.pre('save', function(next){
if (!this.isModified('password')) return next();
var _this = this;
console.log('this.password: ' + this.password); // returns abcd
bcrypt.hash(this.password, secret.pwdHashSecret, null, function(err, hash) {
if(err)
return next(err);
_this.password = hash;
console.log('this.password: ' + _this.password); // returns hashed pwd
next();
});
});