gpt4 book ai didi

javascript - Mongoose |预保存 Hook 中的对象更改不会保存到数据库

转载 作者:太空宇宙 更新时间:2023-11-04 02:05:01 24 4
gpt4 key购买 nike

我遇到了一个无法解决的问题。我将尝试尽可能有意义且简单地描述它。这是我的方法,处理发布请求并保存数据:

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)
)
});

当我将新用户保存到数据库时,会触发此预保存 Hook :

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": "example@example.com",
"password": "somepass"
}

来自预保存 Hook 日志的console.log:

{ __v: 0,
email: 'example@example.com',
password: '$2a$10$tWuuvw.wGicr/BTzHaa7k.TdyZRc5ADDV0X1aKnItvVm6JYVe5dsa',
_id: 59482e8136fd8d2bf41e24b7
}

但是在数据库中我有:

{
"_id" : ObjectId("59482e8136fd8d2bf41e24b7"),
"email" : "example@example.com",
"password" : "somepass",
"__v" : 0
}

显然,对用户对象的更改未保存,并且在 save() 方法中我仍然使用带有未哈希密码的旧值。这是为什么?如何从预保存 Hook 中进行更改以进行存储?

最佳答案

问题是您总是在 if block 之后调用 next(),即使密码需要异步加密也是如此。

更改您的代码以仅对现有用户文档执行此操作:

if(user.isNew){
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(user.password, salt, (err, hash) => {
user.password = hash;
console.log(user);
next();
})
})
}
else {
next();
}

关于javascript - Mongoose |预保存 Hook 中的对象更改不会保存到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44639306/

24 4 0
文章推荐: javascript - React/Electron 渲染组件失败
文章推荐: css - ReactJS 关键 Prop 在 CSS 动画中不起作用
文章推荐: javascript - 如果表 标签为空或 null,如何隐藏整个
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com