Javascript 猫鼬是经过修改的,总是返回false
当我重置密码并将新密码发送到正文中,然后调用updateUserById时,它不会散列密码,而只是将其保存为原样 在控制器中Javascript 猫鼬是经过修改的,总是返回false,javascript,node.js,mongodb,express,mongoose,Javascript,Node.js,Mongodb,Express,Mongoose,当我重置密码并将新密码发送到正文中,然后调用updateUserById时,它不会散列密码,而只是将其保存为原样 在控制器中 export const updateUserById = async (userId, updateBody) => { const user = await getUserById(userId); if (!user) { throw new AppError('User not found', 404); } if (updateBo
export const updateUserById = async (userId, updateBody) => {
const user = await getUserById(userId);
if (!user) {
throw new AppError('User not found', 404);
}
if (updateBody.email && (await User.isEmailTaken(updateBody.email, userId))) {
throw new AppError('Email already taken', 400);
}
User.findOneAndUpdate(userId, updateBody, (err, user) => {
if (err) {
throw new AppError(err, 400);
} else {
user.local.password = updateBody.password;
user.save((err, user) => {
if (err) {
return err;
}
return user;
});
}
});
};
在模型中
userSchema.pre('save', async function (next) {
const user = this.local;
if (user.isModified('password') || this.isNew) {
user.password = await hash(user.password, 32);
}
next();
});
我认为
User.findOneAndUpdate
不会启动预保存?您检查过了吗?我想您可以使用findById,然后点击doc.set(data)和doc.save()
而不是findOneAndUpdate
,这将触发presaveHooks,允许定期执行,这样您就可以使用userSchema.pre(/(?:[uU]pdate | save)/,异步函数(next){…}
以确保在保存
、updateOne
、findOneAndUpdate
等时调用。