我在Express中有一条路线,该路线的功能向mongo集合添加了一些req.body属性信息。它可以工作,但是我对此不满意,这对我来说是错的,而且我认为我还没有意识到异步/等待。
这是代码:
router.post("/input/:id", ensureAuthenticated, async (req, res) => {
Project.findOne({
_id: req.params.id
}).then(project => {
const newInput = {
inputTitle: req.body.inputTitle,
inputValue: req.body.inputValue,
inputUnits: req.body.inputUnits,
inputCategory: req.body.inputCategory,
inputUser: req.user.id
};
// Add to the array, this is the async function
(async () => {
await project.inputs.unshift(newInput);
})();
project.save().then(project => {
res.redirect(`/projects/output/${project.id}`);
});
});
});
该异步函数是否正在执行我认为/希望执行的操作(我希望它在页面重定向之前将newInput变量添加到数据库中)?最好的方法是什么?我应该尝试将所有功能都写成一个功能吗?