简体   繁体   中英

Insert new record using Scala Salat/Casbah and Mongodb

Greetings,

I am using Salat and Casbah to create a user collection in Mongodb , everything works great until I added a unique index on the email field. Now my insert returns a unique id with no actual record added in the DB for existing email addresses. I am new to scala and Casbah/Salat so I apologize if I am asking an obvious question.

here are my collection indexes

db.users.getIndexes()
[
    {
    "v" : 1,
    "key" : {
    "_id" : 1
    },
    "name" : "_id_",
    "ns" : "study_test.users"
    },
    {
    "v" : 1,
    "unique" : true,
    "key" : {
        "email" : 1
    },
    "name" : "users_email",
    "ns" : "study_test.users"
    }
]

and this is my dao object

object UserDao extends SalatDAO[UserModel, ObjectId](collection = MongoUtil.getCollection("study", "users")) {
val logger = LoggerFactory.getLogger(UserDao.getClass)

val dao = this

UserDao.collection.ensureIndex(DBObject("email" -> 1), "users_email", true)
RegisterJodaTimeConversionHelpers()

def create(userContract: UserContract): Option[ObjectId] = {
    val userModel = UserConverter.toModel(userContract)
    dao.insert(userModel)

}
}

I found what the problem was, I upgraded mongodb and casbah 2.10 but used MongoConnection to connect to mongoDB. I switched to connection using mongo client and all works as expected.

What do you mean by "Now my insert returns a unique id with no actual record added in the DB for existing email addresses." Can you specify an example?

Since you have a unique index, insert will fail for a new insert (or whatever the behaviour for scala/casbah is) for the same email id.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM