import com.escalatesoft.subcut.inject._
import com.mongodb.casbah.Imports._
import com.novus.salat._
import com.novus.salat.global._
import com.novus.salat.dao._
case class User(_id: ObjectId = new ObjectId, email: String, password: String)
class UserDAO(coll: MongoCollection = DatabaseClient.getCollection("users")) extends SalatDAO[User, ObjectId](
collection = coll
)
class UserRepository(implicit val bindingModule: BindingModule) extends Injectable {
val userDAO = injectOptional [UserDAO] getOrElse {new UserDAO}
def createUser (email: String, password: String):Option[ObjectId] = {
val newUser = User(email = email, password = password)
val createdUser = userDAO.insert(newUser)
createdUser
}
}
Basically When inserting a new user it returns the Some("ObjectId of new user") which is exactly what I expect it to do. However when I put an Index on the email then I get a duplicate key error. What I would like is instead of getting the duplicate key error, getting the None option just like I do when I read from the collection and there is no matching document.
How can I get a None option when MongoDB returns the duplicate key error?
Or how should I be handling this error that I get back?