Creating a one-many relationship in MongoDB

Mar 30, 23

The most commong thing you wanna do in an database is have relation ship between some objects.

  • A Todo items belongs to a user (Many - 1)
  • A User have multiple Todo items (1 - Many)
  • A User can have only 1 Drivers License (1 - 1)
  • A Book can have multiple Authors and a Author can have multiple Books (Many - Many)

In this short we will learn about 1-Many/Many-1 relationship using TodoScheme and UserSchema

UserSchema

const mongoose = require("mongoose");

const userSchema = new mongoose.Schema({
    email: {
        type: String,
        required: true,
        trim: true,
        unique: true,
        lowercase: true
    },
    password: {
        type: String,
        required: true,
        minLength: 8,
        trim: true
    }
});

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

TodoSchema

const mongoose = require("mongoose");

const todoSchema = mongoose.Schema({
    text: {
        type: String,
        required: true,
        trim: true
    }
}, {
    timestamps: true
});

const Todo = mongoose.model('Todo', todoSchema);

module.exports = Todo;

Above we have to Mongoose Schemas TodoSchema and UserScheme and they do not have any relationship between then as of yet. To create a relationship between them it is a 2 step process.

1. Attach a userId with todoSchema.

The new todoSchema will look something like this:

const todoSchema = mongoose.Schema({
    text: {
        type: String,
        required: true,
        trim: true
    },
    userId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    }
}, {
    timestamps: true
});

2. Add a virtual type in userSchema that will hold todos for that user.

// The relationship between the todos and the user
userSchema.virtual('todos', {
    ref: 'Todo',
    localField: '_id',
    foreignField: 'user'
});

That is all you have to do to create a 1-Many relantion between to MongoDB Collections.