skip to Main Content

I’m not sure why exactly I’m getting this error. Everything seems fine, check the code below.

This is my model class:

@Serializable
actual data class User(
    @SerialName(value = "_id")
    actual val id: String = "",
    actual val username: String = "",
    actual val password: String = ""
)

This is my code:

override suspend fun checkUserExistence(user: User): User? {
    return try {
        userCollection
            .find(
                Filters.and(
                    Filters.eq(User::username.name, user.username),
                    Filters.eq(User::password.name, user.password)
                )
            ).firstOrNull()
    } catch (e: Exception) {
        context.logger.error("checkUserExistence ERROR")
        context.logger.error(e.message.toString())
        null
    }
}

This is the error:

[Thread-16] DEBUG org.mongodb.driver.operation – Unable to retry the
operation find due to the error
"org.bson.codecs.configuration.CodecConfigurationException: Unable to
invoke primary constructor of User data class" 2023-09-09 07:33:26.780
[eventLoopGroupProxy-4-4] ERROR ktor.application – checkUserExistence
ERROR 2023-09-09 07:33:26.780 [eventLoopGroupProxy-4-4] ERROR
ktor.application – Unable to invoke primary constructor of User data
class

2

Answers


  1. Chosen as BEST ANSWER

    Okay so the issue here was the @SerialName(value = "_id") annotation. My best guess is that when a mongodb tries to construct a User object, it doesn't recognize the _id field name which is stored in the database, instead it uses the id as the name of the field, which is not correct? Not sure tho, but mongo folks should take a look into that. Hope this answer helps someone as well. :)


  2. You can fix this by annotating with @BsonProperty e.g

    @Serializable
    actual data class PostLight(
        @SerialName("_id")
        @BsonProperty("_id")
        actual val id: String = ObjectId().toHexString(),
        actual val date: Long,
        actual val title: String,
        actual val subtitle: String,
        actual val thumbnail: String,
        actual val category: String,
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search