I have a mongo collection in which there is a String field called role
. This field in particular will always be filled with one of these three options: user
, admin
or guest
.
This is the reason why I decided to create an enum so it makes it easier for developers to work with it while keeping the String value in the database.
I have tried to retrieve a document from my collection expecting KMongo to be able to parse from String to Enum Role
and vice versa.
Sadly, KMongo does not seem to be able to do it.
data class User(var role: Role, // 0 user, 1 admin, 2 guest
var email: String,
var password: String)
enum class Role{
user,
admin,
guest
}
When I tried to find a document by its _id
I got this message:
2019-05-21 11:39:01 [http-nio-8080-exec-1] ERROR c.p.p.c.SpringWebConfig$simpleMappingExceptionResolver$resolver$1 - Excepción general resolviendo una petición com.fasterxml.jackson.module.kotlin.MissingKotlinParameterException: Instantiation of [simple type, class com.foo.user.User] value failed for JSON property role due to missing (therefore NULL) value for creator parameter role which is a non-nullable type at [Source: de.undercouch.bson4jackson.io.LittleEndianInputStream@3195529c; pos: 275] (through reference chain: com.foo.user.User["Role"])
So my question is: does KMongo support enums in these terms?
So I finally found a solution for my issue. Using the Jackson Annotations library I can serialize and deserialize my enums the way I need. In my case, I chose to use them as Strings so KMongo knows how to work with them.
@JsonFormat(shape = JsonFormat.Shape.STRING)
enum class Role {
user,
admin,
guest
}
Now I can just declare my attributes as my enum type so KMongo knows what to do with them.