How to $push an object using MongoDB with Panache on Quarkus

41 views Asked by At

I'm having trouble pushing an object to a field in my MongoDB document because Panache keeps casting it to a String. Can anyone help me find a solution to this issue?

I have this simple collection with a list I need to push objects into:

@Data
@NoArgsConstructor
@AllArgsConstructor
@RegisterForReflection
@MongoEntity(collection = "library")
public class Library {

    @BsonId
    @BsonProperty("_id")
    private ObjectId id;
    private List<Book> books;
}

@Data
@NoArgsConstructor
@AllArgsConstructor
@RegisterForReflection
public class Book {

    private String name;
}

I started with a straightforward update, assuming that the Book object would be deserialized correctly, but it did not work. I have tried other potential solutions as well, but none of them have been effective up to this point.

update("{ $push: { books: ?1 } }", book).where("_id", libraryId);
/*
"books": [
  "Book(name=This is a book name)",
  "Book(name=This is another book name)"
]
*/

update("{ $push: { books: ?1 } }", new Gson().toJson(book)).where("_id", libraryId);
/*
"books": [
  "{\"name\":\"This is a book name\"}",
  "{\"name\":\"This is another book name\"}"
]
*/

update("{ $push: { books: JSON.parse(?1) } }", new Gson().toJson(book)).where("_id", libraryId);
/*
exception: org.bson.json.JsonParseException: JSON reader was expecting a value but found 'JSON'.
*/

update("{ $push: { books: { $each ?1 } } }", List.of(book)).where("_id", libraryId);
/*
exception: org.bson.json.JsonParseException: JSON reader was expecting ':' but found 'Book(name=This is a book name)'.
*/

If I find the document, manually push the object into the books list and then update the entity (using Uni<Entity> update(Entity entity)) it works as intended, but recovering the whole document beforehand is not an option for performance reasons.

This is what I'm trying to achieve. Is it even possible?

{
  "_id": ObjectId("654a8938bb53e000010bc5d5"),
  "books": [
    {
      "name": "This is a book name"
    },
    {
      "name": "This is another book name"
    }
  ]
}
0

There are 0 answers