Kmongo: how to add unique field

700 Views Asked by At

I have a simple user data class that looks like:

@Serializable
data class User(
@SerialName("_id")
val _id:  Id<User> = newId(),
val email: String,
var password: String,
var tokens: Array<String> = arrayOf()
) 

And I'd like the email value to be unique, i've tried a unique annotation which seemed most appropiate, but with no success. I've also tried google and the KMongo website but I could not find an answer.

1

There are 1 best solutions below

0
On

You need to create an index on the field (or combination of fields) that you want to ensure uniqueness on.

db.getCollection<User>().createIndex(User::email,
    indexOptions = IndexOptions().unique(true))