I tryna save Enum class in Kmongo, but I get error:
A String value cannot be written to the root level of a BSON document. org.bson.BsonInvalidOperationException: A String value cannot be written to the root level of a BSON document.
Here is my code for repository where I have logic for CRUD operations:
class MongoRepo<E>(private val collection: MongoCollection<E>) : Repo<E> {
private val ids = mutableListOf<String>()
override fun create(element: E): Boolean {
Item(UUID.randomUUID().toString(), element)
.let {
ids.add(it.id)
collection.insertOne(it.elem)
}
return true
}
override fun read(): List<Item<E>> {
return collection.find().mapIndexed { index, element ->
Item(ids[index], element)
}.toList()
}
override fun read(id: String): Item<E>? {
return collection.find().mapIndexed { index, element ->
Item(ids[index], element)
}.firstOrNull()
}
override fun read(ids: List<String>): List<Item<E>> =
ids.mapNotNull { id ->
collection.find(Item<E>::id eq id).mapIndexed { index, element ->
Item(ids[index], element)
}.firstOrNull()
}
override fun update(id: String, value: E): Boolean {
collection.updateOneById(id, value as Any)
return true
}
override fun delete(id: String): Boolean {
val query = collection.deleteOneById(id)
return query.deletedCount > 0
}
}
And when I tryna create Enum I get error. Anyone know how to store Enums in Kmongo?
private val grades = mongoDatabase.getCollection<Grade>().apply { drop() }
val gradesRepo = MongoRepo(grades)
Grade.list.apply {
map { gradesRepo.create(it) }
}
My Grade class:
@Serializable
enum class Grade(val mark: Int) {
@SerialName("5")
A(5),
@SerialName("4")
B(4),
@SerialName("3")
C(3),
@SerialName("2")
F(2);
companion object {
val list = listOf(A, B, C, F)
}
}
I also try save Document instead of Grade class, but it print another error — serialization for class Document not found.