Javascript 快速路由器删除与猫鼬不';我不懂ES8语法
我有这个密码:Javascript 快速路由器删除与猫鼬不';我不懂ES8语法,javascript,express,mongoose,async-await,Javascript,Express,Mongoose,Async Await,我有这个密码: router.delete('/:id', (req, res) => { Input.findById(req.params.id) .then(Input => Input.remove().then(() => res.json({ success: true }))) .catch(err => res.status(404).json({ success: false })); }); 由于我们是在2019年,我想我应该转向
router.delete('/:id', (req, res) => {
Input.findById(req.params.id)
.then(Input => Input.remove().then(() => res.json({ success: true })))
.catch(err => res.status(404).json({ success: false }));
});
由于我们是在2019年,我想我应该转向异步/等待语法,我做到了:
router.delete('/:id', async ({ params }, res) => {
try {
const Input = await Input.findById(params.id);
await Input.remove();
res.json({ success: true });
} catch (error) {
res.status(404).json({ success: false });
}
});
ID按预期接收,但由于某种原因,input.findById返回null,有人知道原因吗?您正在使用
常量输入跟踪输入在findById
之前。为它使用不同的名称(即使只是小写就足够了;请记住,最初封顶的标识符主要用于构造函数,而不是非构造函数对象):
如果您愿意,顺便说一句,您可以进行嵌套的解构来挑选id
:
router.delete('/:id', async ({params: {id}}, res) => {
// ^^^^^^^^^^^^^^======================
try {
const input = await Input.findById(id);
// ^=========================
await input.remove();
res.json({ success: true });
} catch (error) {
res.status(404).json({ success: false });
}
});
router.delete('/:id', async ({params: {id}}, res) => {
// ^^^^^^^^^^^^^^======================
try {
const input = await Input.findById(id);
// ^=========================
await input.remove();
res.json({ success: true });
} catch (error) {
res.status(404).json({ success: false });
}
});