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:
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.
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.
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.
