Creating Relationships Between Models

Creating Relationships Between Models

In the past lessons, we learned how to set up MongoDB with Express.js, define Mongoose schemas and models, and manage ToDo items. Today, we'll take a step further and learn about creating relationships between models. Models in MongoDB help us structure our data, but sometimes we need to connect different types of data, like linking todo items to their categories. Creating these connections is crucial for building more complex applications, enabling more detailed queries, such as finding all tasks in a specific category or aggregating tasks by categories in a task management app.

What You'll Learn

In this lesson, you'll learn:

  • What relationships between models are
  • How to create and use references between models
  • How to populate data from related models

Step 1: Connecting to MongoDB

First, we need to connect to MongoDB. We've done this multiple times in previous lessons, so here's the code snippet for reference:

const mongoose = require('mongoose');
const express = require('express');

const app = express();
const PORT = 3000;

// Set mongoose strictQuery to true to suppress deprecation warning
mongoose.set('strictQuery', true);

// Connect to MongoDB, ensure your MongoDB server is running
mongoose.connect('mongodb://127.0.0.1:27017/todo-app', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
})
.then(() => console.log("Connected to MongoDB"))
.catch((error) => console.error("Failed to connect to MongoDB:", error));

app.use(express.json());

In this code, we set up the Express application, and connect to our MongoDB database.

Step 2: Defining Schemas and Models

Next, we'll define the schemas for our Category and ToDo models.

// Define schema for categories
const categorySchema = new mongoose.Schema({
    name: { 
        type: String, 
        required: true,
        trim: true,
        minLength: 3,
        maxLength: 50
    }
});

// Create Category model
const Category = mongoose.model('Category', categorySchema);

In the above schema definition, trim option removes any whitespace from the input. minLength and maxLength ensure the category name stays within the specified length range (3 to 50 characters).

Now, we'll create the ToDo model with a reference to the Category model.

const todoSchema = new mongoose.Schema({
    task: { type: String, required: true },
    category: { type: mongoose.Schema.Types.ObjectId, ref: 'Category' }
});

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

In this step, the category field in our ToDo schema is of type ObjectId and references the Category model, allowing us to link ToDo items with specific categories.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal