多对多建模:通过 Mongoid/MongoDB
我对 Mongoid/MongoDB 比较陌生,我有一个关于如何建模特定的多对多关系的问题。
我有一个 User
模型和一个 Project
模型。用户可以属于多个项目,并且每个项目成员身份都包含一个角色(例如“管理员”、“编辑者”或“查看者”)。如果我使用 ActiveRecord,那么我会使用 has_many :through
在 User
和 Project
之间建立多对多关联,然后我在连接表中放置一个角色字段。
在 MongoDB 中对这种情况进行建模的好方法是什么?我如何使用 Mongoid 声明该模型?下面的示例似乎是对此进行建模的好方法,但我不知道如何使用 Mongoid 优雅地声明 User
和嵌入的 ProjectMembership
之间的关系关联。
提前致谢!
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})
I'm relatively new to Mongoid/MongoDB and I have a question about 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 (eg. "administrator", "editor", or "viewer"). If I were using ActiveRecord then I'd set up a many-to-many association between User
and Project
using has_many :through
and then I'd put a field for role in the join table.
What is a good way to model this scenario in MongoDB and how would I declare that model with Mongoid? The example below seems like a good way to model this, but I don't know how to elegantly declare the relational association between User
and the embedded ProjectMembership
with 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})
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
建模一个好的 Mongodb 模式实际上取决于您访问数据的方式。在您描述的情况下,您将索引您的memberships.user_id 键,这看起来没问题。但是,随着查看者、编辑者和管理员的添加,您的文档大小将会增加。此外,您的架构将很难进行如下查询:
查询项目,其中 user_id xxx 是编辑器:
同样,您可能不需要像这样查询项目,因此您的架构看起来不错。但是,如果您需要通过 user_id 和角色查询您的项目,我建议您创建一个“project_membership”集合:
或者更简单...在项目架构上添加索引:
Modeling a good Mongodb schema really depends on how you access your data. In your described case, you will index your memberships.user_id key which seems ok. But your document size will grow as you will add viewers, editors and administrators. Also, your schema will make it difficult to make querys like:
Query projects, where user_id xxx is editor:
Again, you maybe do not need to query projects like this, so your schema looks fine. But if you need to query your projects by user_id AND role, i would recommend you creating a 'project_membership' collection :
Or even easier... add an index on your project schema: