【发布时间】:2020-10-16 19:45:18
【问题描述】:
我想知道这种使用猫鼬的异步/等待方法是否正确。我仍然需要使用 .exec 然后用猫鼬返回承诺,否则我可以留下这样的东西。这是我的代码sn-p:
这是用户控制器,例如:
/* Func to update one user by id */
const updateUser = async (id, user) => {
const filter = {_id: id};
const update = {name: user.name, email: user.email};
const result = await User.findOneAndUpdate(filter, update, {new: true});
return result;
};
这是路线:
/* PATCH update user passing the id in params */
router.patch('/list/:id/update', async (req, res, next) => {
try {
const data = await usersController.updateUser(req.params.id, {
name: req.body.name,
email: req.body.email,
});
res.status(data ? 200 : 404).json({
result: data,
message: 'User updated',
});
} catch (e) {
res.status(500).json({
result: e.toString(),
});
}
});
这种方法使用 mongoose 是否正确,或者我需要在查询后使用异步调用 .exec().then().catch()?
【问题讨论】:
标签: node.js mongodb express asynchronous mongoose