简体   繁体   中英

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.

    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?

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. 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]
}
  • 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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