首页 > 解决方案 > Express Router delete with mongoose 不适用于 ES8 语法

问题描述

我有这个代码:

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

标签: javascriptexpressmongooseasync-await

解决方案


您正在Inputconst 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 });
  }
});

推荐阅读