我想要做的是:
此HTTP调用更新数据库中的密码。我发送了新密码,以便在getHashedPassword()中进行散列和盐化,这是可行的,至少根据打印散列数字的console.log是这样。
问题:当我用promise的结果重新分配body数据字段时,body数据字段没有更新,这在promise之外的控制台日志中得到了证明。因此,在数据库中,新的文字字符串password会更新,但不会更新散列。我会提供输出和图片,以防我的解释令人困惑。
router.put('/:id', (req, res) => {
getHashedPassword(req.body.password01).then( result => {
console.log('this is the hashed', result);
req.body.password01 = result;
})
console.log('new passwords', req.body.password01);
BasicUser.findByIdAndUpdate(req.params.id, req.body)
.then(user => res.json({ msg: 'Updated successfully' }))
.catch(err =>
res.status(400).json({ error: 'Unable to update the Database' })
);
});Console.logs:
new passwords helloagain339
this is the hashed $2b$10$fPw/bHW69mnyltWh0Qn3T.hKIsxbhgTt8/OGxOQXVVRDpTICqZCy.发布于 2021-11-04 05:26:33
好的,问题是BasicUser.findByIdAndUpdate在getHashedPassword promise解析并返回响应之前运行,这样它就可以传递给findByIdAndUpdate。解决方法是使用async/await或将第二个promise放在第一个promise的回调中。
异步/等待方法
router.put("/:id", async (req, res) => {
try {
req.body.password01 = await getHashedPassword(req.body.password01);
console.log("new passwords", req.body.password01);
const user = await BasicUser.findByIdAndUpdate(req.params.id, req.body);
res.json({ msg: "Updated successfully" });
} catch (error) {
res.status(400).json({ error: "Unable to update the Database" });
}
});嵌套回调方法
router.put("/:id", (req, res) => {
getHashedPassword(req.body.password01).then((result) => {
console.log("this is the hashed", result);
req.body.password01 = result;
console.log("new passwords", req.body.password01);
BasicUser.findByIdAndUpdate(req.params.id, req.body)
.then((user) => res.json({ msg: "Updated successfully" }))
.catch((err) =>
res.status(400).json({ error: "Unable to update the Database" })
);
});
});附言:我建议使用异步等待方法
发布于 2021-11-04 05:27:24
您可以使用async/await使代码更具可读性,如下所示
router.put('/:id', async (req, res) => {
let result = await getHashedPassword(req.body.password);
req.body.password01 = result;
console.log('new passwords', req.body.password01);
BasicUser.findByIdAndUpdate(req.params.id, req.body)
.then(user => res.json({ msg: 'Updated successfully' }))
.catch(err => res.status(400).json({ error: 'Unable to update the Database' }));
});https://stackoverflow.com/questions/69834767
复制相似问题