使用mongoose删除Express Router对ES8语法不起作用

问题描述 投票:1回答:1

我有这个代码:

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年,我认为我应该继续async / await语法,我这样做:

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,有人知道为什么吗?

javascript express mongoose async-await
1个回答
2
投票

你在Input之前用const Input阴影findById。为它使用不同的名称(即使只是小写足够好;记住,最初的上限标识符主要用于构造函数,而不是非构造函数对象):

router.delete('/:id', async ({ params }, res) => {
  try {
    const input = await Input.findById(params.id);
    //    ^-------------------------------------------- here
    await input.remove();
    //    ^-------------------------------------------- and here
    res.json({ success: true });
  } catch (error) {
    res.status(404).json({ success: false });
  }
});

如果你愿意,顺便说一句,你可以做嵌套解构来挑选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 });
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.