【问题标题】:Return by default toString() _id mongo spring boot kotlin默认返回 toString() _id mongo spring boot kotlin
【发布时间】:2021-08-20 04:45:43
【问题描述】:

您好,我是 Kotling 的新成员,我正在使用 mongoDB 作为数据库进行 REST 服务 我试图从数据库及其作品中获取信息,但 _id 显示为对象而不是字符串

回应

[
    {
        "id": {
            "timestamp": 1622599648,
            "date": "2021-06-02T02:07:28.000+00:00"
        },
        "name": "test",
        "description": "test",
        "createdDate": "2021-06-01T21:07:28.385",
        "modifiedDate": "2021-06-01T21:07:28.385"
    },
    {
        "id": {
            "timestamp": 1622600161,
            "date": "2021-06-02T02:16:01.000+00:00"
        },
        "name": "test",
        "description": "test",
        "createdDate": "2021-06-01T21:16:01.669",
        "modifiedDate": "2021-06-01T21:16:01.669"
    }
]

类:

@Document
data class Patient (
        @Id
        
        val id: ObjectId = ObjectId.get(),
        val name: String,
        val description: String,
        val createdDate: LocalDateTime = LocalDateTime.now(),
        val modifiedDate: LocalDateTime = LocalDateTime.now()
        )

interface PatientRepository : MongoRepository<Patient, String> {
        fun findOneById(id: ObjectId): Patient
        override fun deleteAll()
}

如何将 id 转换为字符串?我什么时候检索数据?

【问题讨论】:

  • 我不知道 kotlin 是如何工作的。你提到了spring boot,有时你可能会从ObjectId to String得到一些想法

标签: spring mongodb spring-boot kotlin


【解决方案1】:

您需要使用序列化器将您的 ObjectId 转换为带有 bean 的字符串

@Bean
    fun customizer(): Jackson2ObjectMapperBuilderCustomizer? {
        return Jackson2ObjectMapperBuilderCustomizer { builder: Jackson2ObjectMapperBuilder -> builder.serializerByType(ObjectId::class.java, ToStringSerializer()) }
    }

然后回应:

[
    {
        "id": "60b6e7e03c52e16a1a1b000c",
        "name": "test",
        "description": "test",
        "createdDate": "2021-06-01T21:07:28.385",
        "modifiedDate": "2021-06-01T21:07:28.385"
    },
    {
        "id": "60b6e9e11194486befd09e8c",
        "name": "test",
        "description": "test",
        "createdDate": "2021-06-01T21:16:01.669",
        "modifiedDate": "2021-06-01T21:16:01.669"
    }
]

【讨论】:

    猜你喜欢
    • 2019-03-14
    • 2019-09-26
    • 2021-04-17
    • 1970-01-01
    • 2018-09-21
    • 2015-12-06
    • 2021-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多