【发布时间】:2019-05-31 01:51:35
【问题描述】:
我创建用户,散列他的密码并保存在 mongo 上。当我尝试更新该用户时,我的问题就开始了。目前,当我更新哈希时不会生成,因为我真的不知道该怎么做。
获取我所说的用户的中间件:
exports.userByID = function(req, res, next, id) {
User.findOne(
{
_id: id
},
function(err, user) {
if (err) {
return next(err);
} else {
req.user = user;
next();
}
}
);
};
用户控制器,用于更新用户:
exports.update = async function(req, res, next) {
User.findByIdAndUpdate(req.user.id, req.body, function(err, user) {
if (err) {
return next(err);
} else {
res.json(user);
}
});
};
用户模型的预“保存”:
UserSchema.pre("save", function(next) {
var user = this;
if (user.password) {
var md5 = crypto.createHash("md5");
user.password = md5.update(user.password).digest("hex");
console.log("Password após o save (hasheando):" + user.password);
}
next();
});
我正在使用护照身份验证(“本地”)。已经在控制器更新上尝试过user.save():
user.save();
res.json(user);
但是,没有成功。
【问题讨论】:
-
你在等待
user.save()吗? -
这听起来可能很愚蠢,但您确定该值没有更新吗?您是在数据库中签入,还是仅在控制器中通过
res.json()返回值?另外,你的 pre('save') 函数是否被调用了? -
请不要使用 md5 进行密码散列。蛮力是far too easy。尝试谷歌搜索 argon2 或让 a module 处理散列
-
感谢您的提示。我将使用另一个哈希
标签: node.js mongodb mongoose passport.js