I am new to MongoDB so pardon me if my approch is incorrect. I am building an application where I have created simple role and permission management. There are separate collections for permissions and roles. A role can have multiple permissions and those permissions can belongs to multiple role. typical many to many relationship. I have embed permission in each Role collection as below.
Role collection
db.roles.find().pretty()
{
"_id" : ObjectId("60b6e6dca3b92759976e3037"),
"role" : "Role 1",
"permissions" : [
"60b6e023a3b92759976e3033",
"60b6e055550b3f41692caa2b",
"60b6e07b550b3f41692caa2c"
],
"updated_at" : ISODate("2021-06-02T02:03:08.282Z"),
"created_at" : ISODate("2021-06-02T02:03:08.282Z")
}
Permissions of same role
> db.permissions.find({"_id":{"$in":[ObjectId("60b6e023a3b92759976e3033"), ObjectId("60b6e055550b3f41692caa2b"), ObjectId("60b6e07b550b3f41692caa2c")]}}).pretty()
{
"_id" : ObjectId("60b6e023a3b92759976e3033"),
"permission" : "product_listing",
"label" : "Product Listing",
"level" : 1,
"parent" : null,
"created_at" : ISODate("2021-06-02T01:45:22.287Z"),
"updated_at" : ISODate("2021-06-02T01:45:22.287Z")
}
{
"_id" : ObjectId("60b6e055550b3f41692caa2b"),
"permission" : "stock",
"label" : "Stock",
"level" : 2,
"parent" : ObjectId("60b6e023a3b92759976e3033"),
"created_at" : ISODate("2021-06-02T01:45:22.287Z"),
"updated_at" : ISODate("2021-06-02T01:45:22.287Z")
}
{
"_id" : ObjectId("60b6e07b550b3f41692caa2c"),
"permission" : "previously_bought_icon",
"label" : "Previously bought icon",
"level" : 2,
"parent" : ObjectId("60b6e023a3b92759976e3033"),
"created_at" : ISODate("2021-06-02T01:45:22.287Z"),
"updated_at" : ISODate("2021-06-02T01:45:22.287Z")
}
Now I want something like below
$role->permissions()
should output all the permsion with details as shown above.
I tried belongsToMany, embedMany relationship but didn't work. Seems I am using wrong approch or I should pass some more fields to the elowuent relation. Please help. Thanks in advance.