Pass values from Mono/Flux to methods
I am new to reactive programming concepts. I’m looking at “learning Spring Boot 2.0” and the simple concepts/examples described are understandable. But I don’t know how to use Mono/Flux for more complex use cases.
Some examples of Spring Boot, Mongo, and Project Recor
My model
User
@Id
private String id;
private String login;
Comment
@Id
private ObjectId _id;
private String content;
private String ownerLogin;
So this simple example of getting owner reviews works fine
@GetMapping(params = "login")
@ResponseBody
public Flux<Comment> getAllCommentsByLogin(@RequestParam("login") String login) {
return commentRepository.findByOwnerLogin(login);
};
But if I change the model slightly to store owners by entity ID, retrieving comments by owner won’t be as easy
Comment
@Id
private ObjectId _id;
private String content;
private String ownerId;
My intention is to make the rest controller easy for end users to use, and first find the user entity by logging in, if there are all user comments
@GetMapping(params = "login")
@ResponseBody
public Flux<Comment> getAllCommentsByLogin(@RequestParam("login") String login) {
return commentRepository.findByOwnerId(userRepository.findByLogin(login).map(user2 -> user2.getId())
};
This solution is obviously wrong, but I don’t know if the whole method is wrong or only this one is wrong.
Solution
If you want your userRepository.findByLogin()
to return Mono<User>
, then the code should look like this:
return userRepository.findByLogin(login)
.flatMapMany(user -> commentRepository.findByOwnerId(user.getId()));