What is the correct way of writing endpoint functions for Mongoose with Express?

Issue

Writing the backend API for my app I’ve encountered countless examples of people using both forms of handling errors in their endpoint functions, as presented below:

Option 1:

 export const deleteProject = asyncHandler(async(req, res) => {
        const project = await Project.findByIdAndDelete(req.params.id);

        if(project) {
            res.status(204).send();
        } else {
            res.status(404).json({message: "Project not found"});
            throw new Error('Project not found');
        }
});

Option 2:

 export const deleteBoard = asyncHandler(async(req, res) => {
        try {
            await Board.findByIdAndDelete(req.params.id);
            res.status(204).send();
        } catch(err) {
            res.status(404).json({message: "Board not found"});
            throw new Error('Board not found');
        }
});

To my current understanding, both of those are correct. I wanted to ask – is one of them preferable because of reasons I might not be aware of?

Solution

I prefer option number #2.

Remember findByIdAndDelete can give n types of error so. you need to change your code like this.

export const deleteBoard = asyncHandler(async(req, res, next) => {
    try {
        const board = await Board.findByIdAndDelete(req.params.id);
        if(board)
          return res.status(204).send();
        res.status(404).json({message: "Board not found"});
    } catch(err) {
       // don't throw anything here 
       // throw new Error('Board not found');
       // use next(errmsg) which will call global error handler
       next(err);
    }

Since you don’t need the item after delete, you can use a better function deleteOne or deleteMany.


  const deleted = await Board.deleteOne({ _id: req.params.id }).exec();
  if (deleted.deletedCount) 
      return res.status(204).send();
  res.status(404).json({message: "Board not found"});

Answered By – JustRaman

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published