简体   繁体   中英

MongoDB best practise - One to many relation

According to this post I should embed a "reference": MongoDB relationships: embed or reference?

User.js

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const userSchema = new Schema({
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    createdEvents: ['Event']
});

module.exports = mongoose.model('User', userSchema);

Event.js

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const eventSchema = new Schema({
    title: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    },
    price: {
        type: Number,
        required: true
    },
    date: {
        type: Date,
        required: true
    }
});

module.exports = mongoose.model('Event', eventSchema);

So an embedded event looks like this in the database:

在此处输入图像描述

My Code works but im curious if this is the right way to embed the event. Because every example for one to many relations is made with references and not embedded.

From my experience, using embedding or referencing depends on how much data we are dealing with.

When deciding on which approach to pick, You should always consider:

1- One-To-Few: if you'll have a small number of events added to a user over time, I recommend you to pick the embedding approach as it is simpler to deal with.

2- One-To-Many: if new events are frequently added, you totally should go for referencing to avoid future performance issues.

Why?

When you are frequently adding new events , if they are being embedded inside an user document, that document will grow larger and larger over time. In the future you will probably face issues like I/O overhead. You can catch a glimpse of the evils of large arrays in the article Why shouldn't I embed large arrays in my documents? . Although it's hard to find it written anywhere, large arrays in MongoDB are considered a performance anti-pattern.

If you decide to go for referencing , I suggest reading Building with Patterns: The Bucket Pattern . The article can give you an idea on how to design your user_events collection in a non-relational way.

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