Search code examples
mongodbspring-dataobjectid

How to get String representation of ObjectId from response body?


I am trying to create a simple API which works with MongoDB documents created from this class:

@Document()
data class Student(@Id val id: ObjectId?,
               val firstName: String,
               val secondName: String) {}

And I have a REST controller which returns me Student documents.

{
    "id": {
        "timestamp": 1657005140,
        "date": "2022-07-05T07:12:20.000+00:00"
    },
    "firstName": "Test",
    "secondName": "Test"
}

But I also need a controller which returns me documents by id. How can I put this JSON id with timestamp and date in a request param like /getByName?id= ? Maybe there is a way to get an ID in one-string representation?


Solution

  • The problem is that my ObjectId was serialised.

    To get simple one-string value I needed just to add: @JsonSerialize(using = ToStringSerializer::class)

    So my document looks like this:

    @Document()
    data class Student(
                   @Id
                   @JsonSerialize(using = ToStringSerializer::class)
                   val id: ObjectId?,
                   val firstName: String,
                   val secondName: String) {}