Skip to main content

Command Palette

Search for a command to run...

Mastering Relationships in MongoDB with Mongoose: A Beginner’s Guide

Learn how to design clean database schemas by understanding One-to-One, One-to-Many, and Many-to-Many relationships with real-world examples, best pra

Published
4 min read
Mastering Relationships in MongoDB with Mongoose: A Beginner’s Guide
A

I am an Enthusiastic and self-motivated web-Developer . Currently i am learning to build end-to-end web-apps.

Introduction: What Is a Relationship?

A relationship defines how two or more people, objects, or entities are connected.
In databases — specifically in MongoDB — a relationship represents how two or more collections are connected.

Example:
In a simple Todo Application, you might have:

  • A Tasks collection

  • A Users collection

Each task is assigned to a specific user, thereby establishing a relationship between tasks and users.


Sample Data Structure

Database: TodoAppDB

Collections:

  1. Tasks Collection
javascriptCopyEdit[
  { title: "Drink Water", status: "pending", email: "r@gmail.com" },
  { title: "Drink Milk", status: "pending", email: "n@gmail.com" },
  { title: "Drink Tea", status: "pending", email: "s@gmail.com" },
  { title: "Take class", status: "pending", email: "n@gmail.com" }
]
  1. Users Collection
javascriptCopyEdit[
  { name: "Rohan", email: "r@gmail.com" },
  { name: "Suraj", email: "s@gmail.com" },
  { name: "Nihal", email: "n@gmail.com" }
]

Example Use-Case:
When Suraj opens the app:

javascriptCopyEditconst tasks = TaskModel.find({ email: "s@gmail.com" });
res.json({ tasks });

Different Types of Relationships


1. One-to-One Relationship

  • Definition:
    One document in a collection relates to exactly one document in another collection.

  • Example:
    Users and their StudentProfiles.

  • How to Establish:
    Store the independent collection’s _id inside the dependent collection.

Example:

Users Collection (Independent)

javascriptCopyEdit{ _id: "ath", name: "Suraj", email: "s@gmail.com" }
{ _id: "5tb", name: "John", email: "j@gmail.com" }

Profiles Collection (Dependent)

javascriptCopyEdit{ _id: "mno", user_id: "5tb", MSAT_score: 10, no_of_interviews: 3 }
{ _id: "xoy", user_id: "ath", MSAT_score: 12, no_of_interviews: 1 }

2. One-to-Many Relationship

  • Definition:
    One document is associated with multiple documents in another collection.

  • Example:
    A User can have multiple Tasks.

Example:

Tasks Collection

javascriptCopyEdit{ _id: "abc", title: "Drink Water", status: "pending", user_id: "5tb" }
{ _id: "xyz", title: "Recharge phone", status: "pending", user_id: "5tb" }
{ _id: "yoy", title: "Pay electric bill", status: "pending", user_id: "5tb" }

3. Many-to-Many Relationship

  • Definition:
    Many documents in one collection relate to many documents in another collection.

  • Example:
    Students can enroll in multiple Courses, and Courses can have multiple Students.

Real-Life Example:
In StackOverflow, a question can have multiple tags like JavaScript, MongoDB, etc.


Understanding Entities, Attributes, and Relationships

When designing a database:

  • Entities: Collections like Users, Tasks, Assignments, etc.

  • Attributes: Properties like name, email, title, status.

  • Relationships: How collections are connected (One-to-One, One-to-Many, Many-to-Many).


ER Diagram Basics

An Entity-Relationship (ER) Diagram visually represents:

  • Entities (Collections)

  • Attributes (Fields)

  • Relationships (Links between entities)

Key Symbols:

SymbolMeaning
RectangleEntity (Collection)
OvalAttribute (Field)
DiamondRelationship
Underlined OvalPrimary Key
Double RectangleWeak Entity

Primary Key (PK) and Foreign Key (FK)

CollectionPrimary Key (PK)Foreign Key (FK)
Users_id-
Tasks_iduser_id
Assignments_id-
Submissions_idassignment_id

Practical Example: API Usage

Creating a Task

javascriptCopyEdit/tasks/create?userId=67b6ee6097a9f4c6205bee9c

Server Side:

javascriptCopyEditconst { title, status } = req.body;
const userId = req.query.userId;
TaskModel.create({ title, status, user_id: userId });

Fetching User Tasks

javascriptCopyEdit/tasks?userId=67b6ee6097a9f4c6205bee9c

Server Side:

javascriptCopyEditconst tasks = TaskModel.find({ user_id: req.query.userId }).populate("user");
const user = UserModel.findOne({ _id: req.query.userId });
const username = user.name;
res.json({ tasks, username });

Best Practices for Relationships

  • Populate only necessary fields to optimize performance.

  • Normalize data where frequent updates occur.

  • Embed data where frequent reads happen.

  • Use Mongoose middleware (pre, post) for maintaining integrity.

  • Index frequently queried fields for faster access.


Conclusion

Designing database relationships carefully ensures:

  • Clean data structures

  • Scalable systems

  • Easy-to-maintain codebases

  • Efficient querying

Remember:
ER diagrams, Primary Keys (PK), Foreign Keys (FK), and relationship types are crucial when planning any real-world database.