Hi all, in a domain class, is there a way to get f...
# questions
i
Hi all, in a domain class, is there a way to get from an ‘embedded’ instance to get a reference to its ‘parent’? Suppose you have something like this
Copy code
class User {
  Set<Membership> memberships
  static embedded = ['memberships']
}

class Membership {}
from a
Membership
instance, get the user it belongs to
Copy code
Membership m = getMembershipSomeway()
println m.getParent()    // ?
p
In GORM for MongoDB, embedded documents (like you Membership class) are part of the parent document (User) and do not maintain independent identities or references back to parent. As a result, there is no direct way to automatically access the parent from an embedded instance. However, you can achieve this by manually adding a reference to the parent entity within the embedded document. Here is how you could modify your code:
Copy code
class User {
    Set<Membership> memberships
    static embedded = ['memberships']
    
    def addMembership(Membership membership) {
        membership.user = this  // Manually setting the parent reference
        memberships.add(membership)
    }
}

class Membership {
    User user  // Reference to the parent User
}
Usage:
Copy code
User user = new User()
Membership membership = new Membership()

user.addMembership(membership)  // Set parent reference

Membership m = user.memberships.first()
println m.user   // Prints the parent User instance
Why is this needed? In MongoDB, embedded documents like
Membership
don't exist as standalone documents. There are stored within parent document
User
, meaning you generally access them through the parent. For example:
Copy code
User user = User.get(someUserId)
Membership membership = user.memberships.first()
Without accessing the User first, it's unclear how you would obtain embedded Membership, since embedded objects don't have independent identities. That's why it makes sense to clarify what you're trying to achieve. If you somehow find yourself with a Membership instance in isolation (perhaps through application logic), manually adding a reference to the parent object (as shown) ensures you can always trace back to the parent.:
Copy code
println m.user // Access the parent User
But again, this setup raises the question of how and why you would have an embedded instance without the parent in the first place. Could you share more details on your use case? It would help in tailoring a more specific approach. This approach combines your desire for accessing the parent while also clarifying the usual flow of embedded document access in MongoDB.
Also, please post question on the Stackoverlfow.