You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ktor集成KMongo触发BsonInvalidOperationException求助

问题:KMongo读取嵌套密封类事件模型时出现BSON解析错误

我是MongoDB新手,正在Ktor项目中集成KMongo库来读写事件模型。按照KMongo官方文档的对象映射指南,我定义了mongoId字段,序列化后是名为_id的String类型。

我的事件模型是嵌套在密封类中的数据类,能通过KotlinX-Serialization正常序列化,模型代码如下:

sealed class Event {
    @SerialName("_id") abstract val mongoId: String
    abstract val id: ID.Event
    abstract val dateTime: LocalDateTime

    fun asString() = id.toString()

    sealed class Hiring : Event() {
        @SerialName("_id") abstract override val mongoId: String
        abstract override val id: ID.Event
        abstract override val dateTime: LocalDateTime

        @Serializable
        data class Start(
            override val id: ID.Event,
            override val dateTime: LocalDateTime,
            val hiringDetailsId: ID.HiringDetails
        ) : Hiring() {
            @SerialName("_id") override val mongoId: String = id.asString()
        }
        ...
    }
}

在仓库类中,我初始化MongoDB并调用无参泛型find()从集合中读取所有Event模型:

...
    private val kmongo = KMongo.createClient().coroutine.client
    private val db = kmongo.getDatabase("test")
    private val eventCollection = db.getCollection<Event>().coroutine
    ...
    override suspend fun getAllEvents() = eventCollection.find().toList()

在Main类中,我通过点击触发加载Event数据:

...
val id = ID.Event(UUID())
...
it.on.click {
   runBlocking {
      val events = eventRepo.getAllEvents().toString()
      logger.debug { events }
   }
}

服务器和MongoDB初始化正常,但点击触发读取时出现如下错误:

org.bson.BsonInvalidOperationException: readString can only be called when CurrentBSONType is STRING, not when CurrentBSONType is DOCUMENT.
    at org.bson.AbstractBsonReader.verifyBSONType(AbstractBsonReader.java:689)
    ...(省略部分栈追踪)

根据栈追踪,BSON解析出现问题,但我并未设置过滤条件。通过MongoDB Compass验证,数据库中的对象写入正常:

MongoDB Compass中的事件数据

id字段是软件内部使用的ID.Event类型,_id是MongoDB内部使用的字段,恳请指出可能的问题原因。


内容的提问来源于stack exchange,提问作者ItWillDo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 03:01:01