0

as you see in the topic. What is the REST standard on a delete request if the resource is not found and how to check this?

router.route('/tasks/:id').delete((req, res) => {
    Task.findByIdAndRemove(req.params.id)
        .then(() => {
            // REST Response for deleting content
            res.status(204);
            res.send('');
        })
        .catch(err => {
            res.status(404);
            res.send(err);
        });
});

At this example I can't get the 404 and I don't know why.

Algore87
  • 43
  • 8

1 Answers1

0

You have to check the document you receive in the then callback, like this:

router.route('/tasks/:id').delete((req, res) => {
    Task.findByIdAndRemove(req.params.id)
        .then((task) => {
            if (!task) {
                res.status(404);
                res.send('');
            } else {
                res.status(204);
                res.send('');
            }
        })
        .catch(err => {
            res.status(404);
            res.send(err);
        });
});

It is correct that 404 is usually sent when the document isn't found, also in delete functions. See this question for more info regarding that.

Mika Sundland
  • 18,120
  • 16
  • 38
  • 50
  • That doesn't look clean to me. How can the promise be rejected to get to the catch? – Algore87 Oct 31 '17 at 13:30
  • Not finding the document isn't really an exceptional type of error, thus not handled by the catch. Catch is for exceptions. I would rather return 500 in the catch, not 404. To get into the catch you can throw an error like this: `throw new Error('error due to not found');` inside the `if(!task)`. – Mika Sundland Oct 31 '17 at 14:55