Questions Management – Core Option Service – Build API find options by id of question using Spring WebFlux and Spring Data MongoDB Reactive

Check out the full series of Questions Management tutorial here.

In the previous tutorial, we prepared all the necessary configurations for building API find options by id of question: a Option document object containing the information of an option, an OptionRepository to manipulate MongoDB, an OptionController that defines the Core Option Service APIs will start with “/option” and the connection information to the MongoDB server is configured in the application.properties file. Now, we are going to build this API!

To build API find options by id of question, we will first define a method in the OptionRepository to help us find information about the options based on the id of the question:

Since we are using Spring Data MongoDB Reactive, we do not need to implement this method.

Next, I’m going to add a method to expose a GET request with the request parameter “questionId” with questionId as the id of the question that the options will be belong to:

then use the findByQuestionId() method that we defined in the OptionRepository interface to return as the following:

That’s it! Let’s test it!

Suppose, in the database I have the following options:

Questions Management – Core Option Service – Build API find options by id of question using Spring WebFlux and Spring Data MongoDB Reactive

then when the request with questionId is 5ad5d9d651bd7a0aefa87fb3, the result will look like this:

Questions Management – Core Option Service – Build API find options by id of question using Spring WebFlux and Spring Data MongoDB Reactive

For this API, since everything is Spring Data MongoDB Reactive, we do not need to write Unit Test for the code that we just added.

Add Comment