Creating Relationships in MongoDB using Mongoose
๐ Creating Relationships in MongoDB Using Mongoose
MongoDB is a NoSQL database and does not have traditional foreign key relationships like relational databases. However, with Mongoose (an ODM for MongoDB in Node.js), you can create and manage relationships between documents using references and population.
๐งฐ Types of Relationships in Mongoose
There are two main types of relationships:
Referenced (Normalization)
Documents reference each other by _id.
Good for large datasets and when documents are frequently updated.
Embedded (Denormalization)
One document contains another as a subdocument.
Good for nested, read-heavy data.
๐ Example: Users and Posts
Let’s walk through creating a one-to-many relationship:
One User → Many Posts
๐ 1. Define the Mongoose Schemas
User Schema (referenced style)
javascript
Copy
Edit
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: String,
email: String,
});
module.exports = mongoose.model('User', UserSchema);
Post Schema (referencing user by ID)
javascript
Copy
Edit
const PostSchema = new Schema({
title: String,
content: String,
author: { type: Schema.Types.ObjectId, ref: 'User' },
});
module.exports = mongoose.model('Post', PostSchema);
๐งช 2. Creating and Saving Documents
javascript
Copy
Edit
const User = require('./models/User');
const Post = require('./models/Post');
async function createPost() {
const user = await User.create({ name: 'Alice', email: 'alice@example.com' });
const post = await Post.create({
title: 'My First Post',
content: 'This is a post written by Alice.',
author: user._id,
});
console.log('Post created:', post);
}
๐ 3. Populating the Author Field
To retrieve the post with the user data instead of just the user._id:
javascript
Copy
Edit
const post = await Post.findOne({ title: 'My First Post' }).populate('author');
console.log(post);
Output includes full author info:
json
Copy
Edit
{
"title": "My First Post",
"author": {
"_id": "60...",
"name": "Alice",
"email": "alice@example.com"
}
}
๐งฉ Embedded Documents (Alternative)
In some cases, especially for comments or settings, you may want to embed the data.
javascript
Copy
Edit
const CommentSchema = new Schema({
body: String,
postedAt: Date
});
const PostSchema = new Schema({
title: String,
content: String,
comments: [CommentSchema]
});
With this approach, comments are stored directly inside the Post document.
✅ When to Use Which
Type Use When...
Referenced Data is large or changes frequently
Embedded Data is small, tightly coupled, and read together
๐ Summary
Use ObjectId references and .populate() for normalized relationships.
Use embedded documents for nested, always-accessed-together data.
Mongoose makes it easy to model relational patterns in a non-relational database.
Learn MERN Stack Course in Hyderabad
Read More
API Rate Limiting with Express
Logging with Morgan and Winston
Visit Our Quality Thought Training in Hyderabad
Comments
Post a Comment