I'm using Salat with MongoDB and I'm trying to convert to natural keys to avoid duplicates in the database. The case class I'm using looks somewhat like:
case class Foo(someRelatedId: String, email: String ...)
I would like to add a natural key that consists of someRelatedId+email and have MongoDB use that instead of the default ObjectId. From the documentation I get the feeling it is possible, but I'm still groping around for a working solution. This is in a large part due to my lack of proficiency with Scala itself, I'm sure.
Update: I have a working solution now, but I'm still wondering if it is the best way to go
case class Foo(someRelatedId: String, email: String, naturalKey: String)
object Foo {
def apply((someRelatedId: String, email: String) {
apply(someRelatedId, email, someRelatedId+email)
}
}
And then in package.scala I map to a custom salat context:
implicit val ctx = new Context() {
val name = Some("Custom Context")
}
ctx.registerGlobalKeyOverride(remapThis = "naturalKey", toThisInstead = "_id")
This way I avoid having a mandatory (meaningless) _id field in my domain classes, but I do have to overload apply() on the companion object, which seems a bit clunky.