gorm-mongodb icon indicating copy to clipboard operation
gorm-mongodb copied to clipboard

Strange behaviour when self referencing objects in grails and mongodb

Open chka opened this issue 7 years ago • 3 comments

I have the following self referencing domain class:

package com.test

import org.bson.types.ObjectId

class Category {
    ObjectId id
    String name
    Category parent = null
    static hasMany = [childs: Category]
    static mappedBy  = [ childs: 'childs' ]
}

Then, I create 2 "Category" objects, where the 2nd object becomes child of the first, like this:

def c1 = Category.findByName('category1') ?: new Category(name: 'category1').save(failOnError: true)
def c2 = Category.findByName('category2') ?: new Category(name: 'category2', parent: c1).save(failOnError: true)
c1.addToChilds(c2).save(failOnError: true)

The outcome, is not what I expect and it appears that both objects become the child of the another:

{
    "_id" : ObjectId("5b8d0ba306425e3ee4ff5cf9"),
    "name" : "category1",
    "version" : NumberLong(0),
    "childs" : [ 
        ObjectId("5b8d0ba306425e3ee4ff5cfa")
    ]
}

{
    "_id" : ObjectId("5b8d0ba306425e3ee4ff5cfa"),
    "name" : "category2",
    "version" : NumberLong(0),
    "childs" : [ 
        ObjectId("5b8d0ba306425e3ee4ff5cf9")
    ],
    "parent" : ObjectId("5b8d0ba306425e3ee4ff5cf9")
}

And while I can simply ignore children that are also parents, why I get this odd behavior?

chka avatar Sep 04 '18 09:09 chka

Please provide an example that reproduces the issue

graemerocher avatar Sep 04 '18 10:09 graemerocher

I thought I did gave an example on the original post. I've listed the domain object and the call I'm doing from bootstrap. I've also shown what I see on mongo. I'm using grails 3.3.0 and mongodb 3.4.10. Let me know if you need more info to reproduce it

chka avatar Sep 04 '18 13:09 chka

to speed up debugging, here is a test project that demos this strange behavior: https://github.com/chka/mongoSelfRef

chka avatar Sep 04 '18 13:09 chka