Search code examples
mongodbquarkusquarkus-panachemutiny

How do I persist nested (MongoDB) entities with Panache Reactive and Mutiny?


I am having trouble using Mutiny. I have 2 entities:

public class Rating extends ReactivePanacheMongoEntity {    
    public String name;
}

and

public class Product extends ReactivePanacheMongoEntity {    
    public List<Rating> ratings = new ArrayList<>();
}

Now I would like to create a rating, persist it and add it to the list of ratings of a product.

public Uni<Product> addRatingToProduct(String productId, String name) {

    Rating rating = new Rating();
    rating.name= name;
    Uni<Rating> ratingUni = rating.persistOrUpdate();

    // Now I need to add the rating to the product:
    Uni<Product> productUni = Product.findEntity(productId);

}

I tried something along the lines of

return ratingUni.map(r -> {
    Uni<Product> productUni = Product.findEntity(productId).map(p -> {
        p.ratings.add(r);
        return p;
    });
    return productUni;
});

but these nested maps feel wrong, and the return Type ended up being a nested Uni.

I also tried Uni.combine(), but to no avail...

I thought that switching to a Reactive Programming with mutiny would be easier, but examples are scarce and the quarkus panache docs are rather superficial 😶


Solution

  • I ended up removing the "Relational DB Style" entity-in-another-entity and added a reference to ProductId in Rating (as suggested here)

    public class Rating extends ReactivePanacheMongoEntity {    
        public ObjectId productId;
        public String name;
    }
    

    thus I only need to persist this new entity.