猫鼬|预保存钩子中的对象更改不会保存到db
问题描述:
我遇到了问题,我无法解决。 我会尽力将其描述为尽可能有意义和简单。 这是我的方法,来处理POST请求,并保存数据:猫鼬|预保存钩子中的对象更改不会保存到db
app.post('/users/', (req, res) => {
let body = _.pick(req.body, ["email", "password"]);
let user = new User(body);
user.save().then(
user => res.json(user),
err => res.send(err)
)
});
当我保存新的用户数据库,这预存钩火灾:
userSchema.pre('save', function(next) {
var user = this;
if(user.isNew){
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(user.password, salt, (err, hash) => {
user.password = hash;
console.log(user);
next();
})
})
}
next();
})
对于POST身体此输入:从预保存钩日志
{
"email": "[email protected]",
"password": "somepass"
}
的console.log:
{ __v: 0,
email: '[email protected]',
password: '$2a$10$tWuuvw.wGicr/BTzHaa7k.TdyZRc5ADDV0X1aKnItvVm6JYVe5dsa',
_id: 59482e8136fd8d2bf41e24b7
}
然而,在分贝我有:
{
"_id" : ObjectId("59482e8136fd8d2bf41e24b7"),
"email" : "[email protected]",
"password" : "somepass",
"__v" : 0
}
用户对象上显然不保存更改并在save()方法我仍然使用旧的价值观念与散列的口令。这是为什么?我怎样才能从预存储钩子进行更改存储?
答
问题是,即使在密码需要异步加密时,您总是在if
块后呼叫next()
。
更改代码,只做到这一点对现有user
文档:
if(user.isNew){
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(user.password, salt, (err, hash) => {
user.password = hash;
console.log(user);
next();
})
})
}
else {
next();
}
我简直不能相信我没有弄清楚它在我自己的。这非常愚蠢。 JohnnyHK非常感谢!最好的祝福! – kkotula