Check out the full series of Questions Management tutorial here.
In the previous tutorial, we prepared all the necessary configurations to build API delete options by question id such as a Option document object containing the information of an option, an OptionRepository to manipulate MongoDB, an OptionController defines the Core Option Service APIs that will start with “/option” and the connection information to the MongoDB server is configured in the application.properties file. Now, let’s build this API!
To build the API to remove options by question id, I would add a new method in the OptionController class to expose a DELETE request with the request parameter “questionId”. questionId is the id of the question that we need to delete:
1 2 3 4 |
@DeleteMapping("") public Mono<ResponseEntity<Void>> deleteByQuestionId(@RequestParam String questionId) { } |
The steps to delete options by question id include:
First, we will find all the options of this question id using the findByQuestionId() method in the OptionRepository class.
1 |
optionRepository.findByQuestionId(questionId) |
For each record returned, we will use the delete() method of the OptionRepository to delete that record.
1 2 |
optionRepository.findByQuestionId(questionId) .flatMap(o -> optionRepository.delete(o)) |
Here, don’t care we are having the options belong to this question id that we need to delete or not, we will also return status as HTTP 200 OK.
1 2 3 |
return optionRepository.findByQuestionId(questionId) .flatMap(o -> optionRepository.delete(o)) .then(Mono.just(new ResponseEntity<Void>(HttpStatus.OK))); |
The entire contents of the deleteByQuestionId() method will now look like this:
1 2 3 4 5 6 |
@DeleteMapping("") public Mono<ResponseEntity<Void>> deleteByQuestionId(@RequestParam String questionId) { return optionRepository.findByQuestionId(questionId) .flatMap(o -> optionRepository.delete(o)) .then(Mono.just(new ResponseEntity<Void>(HttpStatus.OK))); } |
Here we have completed the construction of the API remove the options by question id for Core Option Service, let’s test it!
Suppose I currently have the following options:
the when I delete all options with question id is 5b4bd6ff2da618063872fc3b, the result will be: