gpt4 book ai didi

Unable to invoke primary constructor of data class - MongoDB Kotlin Driver(无法调用数据类的主构造函数-MongoDB Kotlin驱动程序)

转载 作者:bug小助手 更新时间:2023-10-25 22:06:55 26 4
gpt4 key购买 nike



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



更多回答

Not sure if you have fully resolved this but in my case I had the same error and I fixed it, here is what I found : Both the Kotlin data class and MongoDB doc have to be in complete parity and neither of them should have any additional or missing fields.

我不确定您是否已经完全解决了这个问题,但在我的例子中,我遇到了相同的错误,我修复了它,以下是我发现的:Kotlin数据类和MongoDB文档都必须是完全对等的,并且它们都不应该有任何额外的或缺少的字段。

优秀答案推荐

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. :)

好的,这里的问题是@SerialName(Value=“_id”)注释。我最好的猜测是,当MongoDB尝试构造User对象时,它不识别存储在数据库中的_id字段名,而是使用id作为字段名,这是不正确的?虽然不确定,但芒果人应该看看这个。希望这个答案对某些人也有帮助。:)



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

您可以通过使用@BsonProperty进行注释来修复此问题,例如


@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,
)

更多回答

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com