Many-to-many modeling: through Mongoid / MongoDB

I'm relatively new to Mongoid / MongoDB, and I have a question on how to model a specific many-to-many relationship.

I have a User model and a Project model. Users can belong to many projects, and each project membership includes one role (for example, "administrator", "editor" or "viewer"). If I used ActiveRecord, I would establish a many-to-many relationship between User and Project using has_many :through , and then I would put the field for the role in the connection table.

What is a good way to model this script in MongoDB and how can I declare this model with Mongoid? The example below seems like a good way to model this, but I don't know how to gracefully declare a relational relationship between User and the built-in ProjectMembership using Mongoid.

Thanks in advance!

 db.projects.insert( { "name" : "Test project", "memberships" : [ { "user_id" : ObjectId("4d730fcfcedc351d67000002"), "role" : "administrator" }, { "role" : "editor", "user_id" : ObjectId("4d731fe3cedc351fa7000002") } ] } ) db.projects.ensureIndex({"memberships.user_id": 1}) 
+4
source share
1 answer

Modeling a good Mongodb schema really depends on how you access your data. In this case, you will index your member. User_id that looks ok. But the size of your document will grow as you add viewers, editors and administrators. In addition, your schema will make queries more difficult:

Request projects, where user_id xxx is the editor:

Again, you may not need to request such projects, so your schema looks fine. But if you need to request your projects using user_id AND role, I would recommend that you create a collection of "project_membership":

 db.project_memberships.insert( { "project_id" : ObjectId("4d730fcfcedc351d67000032"), "editors" : [ ObjectId("4d730fcfcedc351d67000002"), ObjectId("4d730fcfcedc351d67000004") ], "viewers" : [ ObjectId("4d730fcfcedc351d67000002"), ObjectId("4d730fcfcedc351d67000004"), ObjectId("4d730fcfcedc351d67000001"), ObjectId("4d730fcfcedc351d67000005") ], "administrator" : [ ObjectId("4d730fcfcedc351d67000011"), ObjectId("4d730fcfcedc351d67000012") ] } ) db.project_memberships.ensureIndex({"editors": 1}) db.project_memberships.ensureIndex({"viewers": 1}) db.project_memberships.ensureIndex({"administrator": 1}) 

Or even simpler ... add an index to the project diagram:

 db.projects.ensureIndex({"memberships.role": 1}) 
+3
source

Source: https://habr.com/ru/post/1342489/


All Articles