Good day All,
I am using the latest Kotlin Coroutine driver (org.mongodb:mongodb-driver-kotlin-coroutine:4.10.2) to connect to my local MongoDB instance (running locally via docker).
Following the quick start guides I am able to connect to DB, send a ping and create a new empty collection with no issues.
But when I try to insert a new record to my new collection, I get a codec not found error:
org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for CodecCacheKey{clazz=class com.example.kotlinmongo.SampleEntity, types=null}.
My entity type is a fairly trivial data class, which contains a single String field and according to the following page kotlin data classes are supposed to be serialized/de-serialized out-of-the-box using a default codec.
I tried a data class only with primitive types, I tried it with @BsonId field, tried with and without kotlinx serialization library in the project - same result.
I am using JDK17 and Kotlin 1.8.
Am I missing something or found a bug?
Here’s a sample code repo to reproduce the problem:
Update: it appears that this issue is only occurring when running in a SpringBoot.
I tried to run my code from a plain gradle project and everything worked fine.
Note: I did not use Spring Data (which has its own mongo libs) at all.
Haven’t got to the bottom of why this is happening under Spring though…
I discovered that Spring Boot had configured Gradle to pull an old version of the MongoDB Kotlin Drivers (4.8.2), I could not figure out why. This driver does not properly support Kotlin data classes, so I needed to manually add an additional dependency on a few Mongo projects.
// MongoDB
implementation("org.mongodb:mongodb-driver-core:5.1.3") {
because("Spring pulls 4.8.2 by default which does not support Kotlin. Have I mentioned that Spring is terrible.")
}
implementation("org.mongodb:bson:5.1.3") {
because("Spring pulls 4.8.2 by default which does not support Kotlin.")
}
implementation("org.mongodb:mongodb-driver-reactivestreams:5.1.3") {
because("Spring pulls 4.8.2 by default which does not support Kotlin.")
}
After this, the default codec properly worked with data classes, without needing to even specify.