ilPittiz
10/07/2024, 3:19 PMclass User {
Set<Membership> memberships
static embedded = ['memberships']
}
class Membership {}
from a Membership instance, get the user it belongs to
Membership m = getMembershipSomeway()
println m.getParent() // ?puneetbehl
10/08/2024, 7:58 AMclass 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:
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:
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.:
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.puneetbehl
10/08/2024, 7:59 AM