如何在猫鼬中建立多对多关系? [英] how to structure many-to-many relationships in mongoose?

查看:69
本文介绍了如何在猫鼬中建立多对多关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用中,用户具有事件和组-事件可以(但不必)属于组.我仍然对非关系型DB还是陌生的,所以我想知道最佳实践,以最佳地构造它.

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.

    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: ????
    });

我只保留一个引用组ID的数组吗?

Do I just keep an array with references to the id of group?

如果这样做,我如何按组查找事件?

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?

推荐答案

在mongodb中,您有两种选择.嵌入(子文档)与链接(另一个集合)

In mongodb, you have two choices. Embedding (subdocument) Vs Linking (another collection)

嵌入与链接 每种方法都各有利弊.

Embedding Vs Linking There are pros and cons with each approach.

嵌入: 您将其嵌套在文档中.

Embedding: You nest it inside the document.

例如,您的文档可能看起来像

for instance, your document might look like

{
    name : 'name',
    events: [a,b,c],
    groups: [1,2,3]
}

  • 您会获得原子性,因为只涉及一个集合.
  • 但是,值可能会重复
  • 链接

    在这里您链接有一种外键. 参考文档

    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.

    如果您要更新组和更新事件,并且它们位于单独的集合中,则必须自己处理原子更新. Mongodb不会为您保证.

    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.

    这篇关于如何在猫鼬中建立多对多关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆