I would like your help. I'm working with Spring reactive (WebFlux) and mongoDB also reactive.
In my model I have an association of two entities: User and Post. Modeling the problem, 1 User has a list of associated Posts (One-to-Many reference), according to example below:
@Document(collection = "user")
public class User {
@Id
private String id;
private String name;
private String email;
@DocumentReference(lazy = true)
private List<Post> posts;
@Document(collection = "post")
public class Post {
@Id
private String id;
private Instant date;
private String title;
private String body;
I'm seeding the DB and including a User and an Array of associated Posts, as shown in the image below:
https://drive.google.com/file/d/1Z72me8Ga9K6MNaFxv4A1sT801K6zzC_J/view?usp=share_link
The problem is when I try to access the List associated with the user. When I find all posts of the User, the object returned always comes with a null reference.
Below is the method where I call findPosts to get a List and it returns the null object reference.
public Flux<PostDTO> findPosts(String id) {
return repository.findById(id)
.flatMapMany(existingUser -> {
if (existingUser.getPosts().isEmpty())
Flux.empty();
List<PostDTO> list = existingUser.getPosts()
.stream().map(x -> new PostDTO(x)).toList();
return Flux.fromIterable(list);
})
.switchIfEmpty(Mono.error(new ResourceNotFoundException("Recurso não encontrado")));
}
java.lang.NullPointerException: Cannot invoke "java.util.List.isEmpty()" because the return value of "com.devsuperior.workshopmongo.entities.User.getPosts()" is null
Looking for this problem here on stackoverflow, I saw some questions that are unanswered, according to the examples and on the internet as a whole, there are very few examples using association of entities.
Spring Data MongoDB not able to load reference collection (@DocumentReference)
How to get duplicate data using @DocumentReference in Spring Data MongoDB?
Could you help me, with tips or even with similar examples?
I was stuck on the same problem for a couple of days until I convince myself that I should to read the manual, then I found it. :'(
https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mapping-usage.document-references