I have some code to delete a recipe from my mongoDB database:
@RequestMapping(value = "/recipe/{id}", method = RequestMethod.DELETE)
public String deleteSingleRecipe(@PathVariable("id") String recipeId) {
try {
repository.deleteById(recipeId);
return "Deleted RECIPE success";
} catch (Exception ex) {
return ex.toString();
}
}
This is able to successfully delete a recipe based on ID. However, I'm unsure how to catch cases such as if the recipe doesn't even exist, or if the deletion is failed.
With JavaScript/Node this was really easy because I could pass a callback function with depending on if result/error were null I could determine the success of the query and proceed. I'm pretty lost how to do this in Java/Spring.
When I tried to delete a recipe a 2nd time I still got "Deleted RECIPE success".
You can add a check before using existsById
boolean isFound = repository.existsById(recipeId);
Returns whether an entity with the given id exists.