简体   繁体   English

如何在猫鼬中建立多对多关系?

[英]how to structure many-to-many relationships in mongoose?

In my app, users have events and groups - and events can (but don't need to) belong to groups. 在我的应用中,用户具有事件和组-事件可以(但不需要)属于组。 I'm still new to non-relational DBs, so I'd like to know best practices for optimally structuring this. 我仍然对非关系型DB还是陌生的,所以我想知道最佳实践,以最佳地构造这种关系。

    var user = new mongoose.Schema({
        name: { type: String },
        events: [event],
        groups: [group]
    });

    var group = new mongoose.Schema({
        name: { type: String }
    });

This is where I'm confused. 这就是我感到困惑的地方。

    var event = new mongoose.Schema({
        name: { type: String }
        groups: ????
    });

Do I just keep an array with references to the id of group? 我是否只保留引用组ID的数组?

If I do that, how would I find events by group? 如果这样做,我如何按组查找事件?

And if a group is deleted, would I have to iterate over each event to remove the reference? 如果删除了一个组,是否需要遍历每个事件以删除引用?

In mongodb, you have two choices. 在mongodb中,您有两种选择。 Embedding (subdocument) Vs Linking (another collection) 嵌入(子文档)与链接(另一个集合)

Embedding Vs Linking There are pros and cons with each approach. 嵌入vs链接每种方法都有其优缺点。

Embedding: You nest it inside the document. 嵌入:将其嵌套在文档中。

for instance, your document might look like 例如,您的文档可能看起来像

{
    name : 'name',
    events: [a,b,c],
    groups: [1,2,3]
}
  • you get atomicity, since only one collection is involved. 您将获得原子性,因为仅涉及一个集合。
  • however, values might be duplicated 但是,值可能重复

Linking 连结中

Here you link with a kind of Foreign key. 在这里,您链接有一种外键。 Refer to docs 参考文档

Documents in one collection will reference documents in another collection. 一个集合中的文档将引用另一个集合中的文档。 Disadvantage is that you lose atomic operations. 缺点是您失去原子操作。 However, you eliminate duplication. 但是,您消除了重复。

If you want to update groups, and update events, and they are in separate collections, you'll have to handle atomic updates yourself. 如果要更新组并更新事件,并且它们位于单独的集合中,则必须自己处理原子更新。 Mongodb will not guarantee it for you. Mongodb不会为您保证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM