RESTful API for HTTP DELETE doesnt check for null

248 Views Asked by At

Im currently writing a RESTful API for a webservice but im having trouble. Im trying to delete an mail, but first i want to check if the mail even exists. My problem is that it doesn't check if mail is null and doesn't respond with a 404. Im working with express and mongoose

router.delete('/:id', (req, res) => {
    const { id } = req.params;
    Mail.findById(id)
      .exec()
      .then((mail) => {
        if (!mail) {
          console.log(mail) // returns null
          return res.status(404);
        }
      })
      .then(
        Mail.deleteOne({ _id: id })
          .exec()
          .then(() => {
            res.status(200).json({
              message: 'Mail deleted',
            });
          })
          .catch((err) => {
            res.status(500).json({ error: err });
          })
      );
  });
1

There are 1 best solutions below

2
On BEST ANSWER

I think you have to do the the deletion part of the code inside the first then block as an else statement. You are not returning anything that the next then block can use.

you could do:

Mail.findById(id)
      .exec()
      .then((mail) => {
        if (!mail) {
          console.log(mail) // returns null
          return res.status(404).send() //need to send response;
        }
        Mail.deleteOne({ _id: id })
          .exec()
          .then(() => {
            res.status(200).json({
              message: 'Mail deleted',
            });
          })
      }).catch((err) => {
            res.status(500).json({ error: err });
      })

PRO TIP: if you don't know it, learn async await. Code will look much cleaner!

Then it would look like this:

router.delete('/:id', async (req, res) => {
    const { id } = req.params;

    try {
      const mail = await Mail.findById(id);
      if(!mail) {
         return res.status(404).send();
      }

      await Mail.deleteOne({_id: id});      
      res.status(200).json({
              message: 'Mail deleted',
            });
    } catch(e) {
      res.status(500).json({ error: err });
    }