Strange behaviour when self referencing objects in grails and mongodb
- Dominant language
- Groovy
- Stars
- 2.9k
- Forks
- 975
- Avg merge
- 1d 22h
- Merged PRs (30d)
- 92
Description
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?
Contributor guide
Research direction
Start with the Category self-reference, its hasMany and mappedBy declarations, and the shown sequence that creates, links, and saves c1 and c2. Reproduce it against MongoDB and compare the persisted parent and childs references; done means explaining why both documents contain the reciprocal reference or identifying the mapping behavior responsible.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- mongodb
- Domain
- database
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100