0
votes

I'm following the tutorials https://quarkus.io/guides/rest-data-panache and https://quarkus.io/guides/mongodb-panache to implement a simple MongoDB entity and resource with Quarkus Panache MongoDB.

Here's what I have so far:

@MongoEntity(collection = "guests")
class GuestEntity(
    var id: ObjectId? = null,
    var name: String? = null
)

@ApplicationScoped
class GuestRepository: PanacheMongoRepository<GuestEntity>

interface GuestResource: PanacheMongoRepositoryResource<GuestRepository, GuestEntity, ObjectId>

When running this, I can create a document by calling

POST localhost:8080/guest
Content-Type: application/json

{
  "name": "Foo"
}

The response contains the created entity

{
  "id": {
    "timestamp": 1618306409,
    "date": 1618306409000
  },
  "name": "Foo"
}

Notice, how the id field is an object whereas I would like it to be a string.

2

2 Answers

2
votes

It turns out that the application was using quarkus-resteasy instead of quarkus-resteasy-jackson.

Once the proper dependency was in place, everything worked as expected

0
votes

To serialize the id field as a String, apply the following annotation to the id field:

import com.fasterxml.jackson.databind.annotation.JsonSerialize
import io.quarkus.mongodb.panache.jackson.ObjectIdSerializer

@MongoEntity(collection = "guests")
class GuestEntity(
    // important: apply the annotation to the field
    @field:JsonSerialize(using = ObjectIdSerializer::class)
    var id: ObjectId? = null,
    var name: String
)

Now the response is

{
  "id": "607567590ced4472ce95be23",
  "name": "Foo"
}