Alexander
Alexander

Reputation: 1378

Express Router delete with mongoose doesn't work on ES8 syntax

I had this code :

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

since we are in 2019, I thought I should move on to async/await syntax and I did this:

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

the ID is recieved as expected, but for some reason the input.findById returns null, anyone knows why?

Upvotes: 2

Views: 49

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074465

You're shadowing Input with const Input prior to findById. Use a different name for it (even just lower case is good enough; remember, initially-capped identifiers are primarily for constructor functions, not non-constructor objects):

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

If you like, btw, you can do nested destructuring to pick out 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 });
  }
});

Upvotes: 2

Related Questions