I am doing a delete of a user and it works by placing his id in req.params.id. However, when doing the delete again to the same id it sends a null, I want to know if it is possible to handle errors that return a user that does not exist and not just null When doing get of the deleted user it also indicates null and I want to send a user not found error how can I do to return an error and not just null.
Here is the example I have:
// eliminar Usuario
router.delete("/usuario/:id", async (req, res) => {
const { id } = req.params;
UsuarioSchema
.findByIdAndRemove({ _id: id })
.then((data) => await = res.status(200).send("usuario eliminado con exito" + data))
.catch((error) => res.status(404).send("usuario no encontrado" + error));
});
This code works for me, it deletes a user from my database, but when I run it again it doesn't give me an error, it sends me a status 200 but with a null user. That's why I want to add an error handling that if the user is null it also tells me that it doesn't exist.
Not finding a data does not mean that there was an error (natively). You must specify that it sends an error.