0

Using Micronaut data to perform the below operations

  1. Find the item with id and subcategory id
  2. Update the subcategory item based on category id and sub-category id
  3. Delete the subcategory item based on category id and sub category id

I have the below data structure

{
        "id": "625a8d1a23c8feb3234fbf28",
        "name": "Category 1",
        "description": "Category 1 description",
        "subCategory": [{
                "id": "625a8d6fe0e3cff6e8a3b795",
                "name": "Sub Category 1",
                "description": "Sub Category 1 description"
            },
            {
                "id": "625a8d782672979b1482f5ca",
                "name": "Sub Category 2",
                "description": "Sub Category 2 description"
            }
        ]
    }

There is a custom query builder in micronaut as describe here https://micronaut-projects.github.io/micronaut-data/latest/guide/#mongoCustomQueries and https://micronaut-projects.github.io/micronaut-data/latest/guide/#mongoCriteriaExecuteQuery

@Introspected
public record SubCategorySpecification() {
    public static PredicateSpecification<Category> categoryAndSubCategoryIdEquals(ObjectId categoryId, ObjectId subCategoryId) {
        return (root,criteriaBuilder) -> {
            criteriaBuilder.equal(root.get("id"), categoryId);
            return criteriaBuilder.and(criteriaBuilder.equal(root.get("subCategory.id"), subCategoryId));
        };
    }
}

I tried the above code and got an exception as Cannot query entity [Category] on non-existent property: subCategory.id and not sure how to write the custom query using @ MongoFindQuery

San Jaisy
  • 15,327
  • 34
  • 171
  • 290

1 Answers1

0

You might need to have the subcategory defined as embedded to be properly recognized.

It's possible to define a custom query:

   @MongoFindQuery("{ $and: [{\"_id\": :categoryId}, {\"subCategory.id\": :subCategoryId}]")
   List<Category> customFind(ObjectId categoryId, ObjectId subCategoryId);

In a similar way, you can use @MongoUpdateQuery and @MongoDeleteQuery. For the syntax check official MongoDB documentation.

Denis
  • 603
  • 4
  • 8