嗨我只想在密码更改时使用哈希密码保存,所以我在预先保存时使用了isModified函数,但即使我更改了密码,它也始终返回false。我试图这样做的原因是因为我不想在更改其他属性时更改并保存我的密码。
router.post('/changepw', isAuthenticated, function (req, res, next) {
User.findOneAndUpdate({_id: req.user._id}, {$set: req.body},{ new: true }, function (err, user){
if (err) {
return err;
}
else {
if (req.body.password) {
user.password = req.body.password;
user.save();
} else {
}
}
res.redirect('/profile');
});
});
就像这里一样,当我改变毕业价值时,我不想更改密码。
router.post('/edit', isAuthenticated, function (req, res, next) {
User.findOneAndUpdate({
_id: req.user._id
}, {
$set: {
name: req.body.name,
phone: req.body.phone,
classc: req.body.classc,
major: req.body.major,
minor: req.body.minor,
linkedin: req.body.linkedin,
bio: req.body.bio
}
}, {
new: true
}, function (err, user, done) {
if (err) {
return err;
} else {
if (typeof req.body.graduated == 'undefined') {
user.graduated = false;
} else if (typeof req.body.graduated == 'string') {
user.graduated = true;
}
user.save();
}
res.redirect('/profile');
});
});
userSchema.pre('save', function(next) {
console.log(this.isModified('password'));
if(this.password && this.isModified('password')){
this.password = bcrypt.hashSync(this.password, bcrypt.genSaltSync(8),null);
}
next()
});
有什么建议吗?
答案 0 :(得分:2)
尝试一下
userSchema.pre('save', async function (next) {
// Only run this function if password was moddified (not on other update functions)
if (!this.isModified('password')) return next();
// Hash password with strength of 12
this.password = await bcrypt.hash(this.password, 12);
//remove the confirm field
this.passwordConfirm = undefined;
});
答案 1 :(得分:0)
请注意,当您使用findAndUpdate()
方法时,不会触发预保存挂钩。使用新的钩子检查Mongoose文档:http://mongoosejs.com/docs/middleware.html#notes。