【问题标题】:Express Router delete with mongoose doesn't work on ES8 syntaxExpress Router delete with mongoose 不适用于 ES8 语法
【发布时间】:2019-08-21 07:09:27
【问题描述】:

我有这个代码:

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】:

    您在 findById 之前使用 const Input 跟踪 Input。为它使用不同的名称(即使只是小写也足够了;请记住,最初加盖的标识符主要用于构造函数,而不是非构造函数):

    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 });
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2021-01-19
      • 1970-01-01
      • 2017-10-19
      • 1970-01-01
      • 1970-01-01
      • 2012-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多