Environment:
This is my (simplified) domain class
class Cluster {
String name
String slug
static constraints = {
name blank: false, unique: true
slug blank: false, unique: true, validator: { return it == it.toLowerCase().replaceAll(/[^\w-]/, '') }
}
static mapping = {
collection 'Cluster'
id name: 'slug'
}
}
As you can see I mapped the slug
property to be the document _id
.
I can successfully add a document with
Cluster cluster = new Cluster(name: 'Dallas', slug: 'dal05')
cluster.insert(failOnError: true)
and everything works fine. But if I execute the same insert
command again I get a duplicated key exception:
com.mongodb.MongoBulkWriteException: Bulk write operation error on server localhost:27017. Write errors: [BulkWriteError{index=0, code=11000, message='E11000 duplicate key error index: db.Cluster.$_id_ dup key: { : "dal05" }', details={ }}]
while I would have expected a simple validation error, stating duplicated key.
However, although the unique
constraint fails, validation is correctly triggered for the other two (empty value or e.g. 'Dal05' -capital letters not allowed-).
Without mapping the id on slug
property, so leaving the default assigned
logic, everything works as expected.
Am I missing something? Thanks in advance!
It seems this is actually a bug, scheduled to be fixed in upcoming GORM release 6.1.5.
Ref. issue: https://github.com/grails/grails-data-mapping/issues/951