Alexandre Bourlier
Alexandre Bourlier

Reputation: 4128

Grails - MongoDB and custom dirty checking

I am using MongoDB and Spring Security Core and UI on my application. Nearly everything works perfectly, except this bit:

    def beforeUpdate() {
        if (isDirty('password')) {
            encodePassword()
        }
    }

which is part of the User domain class. I have read that dirty checking was not supported by the MongoDB plugin yet. So I tried to implement my own like this:

if ( User.collection.findOne(id:id).password != password ) {
            encodePassword()
        } 

But it is not working. I get the classical Cannot get property 'password' on null object.

Does anyone know how to reference an instance from the domain class definition ? I am also open to any better idea to implement the dirty checking.

Upvotes: 4

Views: 1250

Answers (4)

Pieter Malan
Pieter Malan

Reputation: 63

I struggled with this issue as well - here is my solution:

def beforeUpdate() {
    User.withNewSession {
        def user = User.findByUsername(this.username)
        if ( !user?.password || user?.password != password) {
            encodePassword()
        }
    }
}

Please let me know if there is a more efficient way.

Upvotes: 0

amit
amit

Reputation: 2061

User.collection.findOne(_id:id).password

Upvotes: 0

Andre
Andre

Reputation: 11

I just hit the same problem, until the dynamic methods work, this will have to do:

def mongo
def beforeUpdate() {
    def persisted = mongo.getDB("test").user.findOne(id).password
    def encodedNew = springSecurityService.encodePassword(password)
    if(persisted != encodedNew) password = encodedNew
    //if (isDirty('password')) {
    //  encodePassword()
    //}
}

Upvotes: 0

Graeme Rocher
Graeme Rocher

Reputation: 7985

Maybe findOne is returning null? Did you try:

def existing = User.collection.findOne(id:id)?.password 
if ( !existing || existing != password ) 

Upvotes: 2

Related Questions