Examples of Relation Mapping with Mongoose
Examples of Relation Mapping with Mongoose
Relation mapping with Mongoose is an effective method used to manage relationships between collections on MongoDB and to create more flexible data structures. Especially in NoSQL's document-based architecture, it is important to model the concept of relational data correctly. In this article, we cover types of relation mapping with Mongoose and practical examples.
Relationship (Relation) Types with Mongoose
Although in MongoDB data is generally stored without relations, in many real-world scenarios it is necessary to establish important connections between collections. Relation mapping with Mongoose is generally done in two ways:
- Reference (Population): One document references another document with ObjectId (similar to a foreign key in RDBMS).
- Embedded: The data of one collection is stored directly inside another collection (through data duplication).
Example of Reference Relationship (Population)
The most commonly used approach is relationships via reference. For example; suppose you have a User and a Post collection. The Post belongs to the user:
// user.js
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: String,
email: String
});
module.exports = mongoose.model('User', userSchema);
// post.js
const mongoose = require('mongoose');
const postSchema = new mongoose.Schema({
title: String,
content: String,
user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
});
module.exports = mongoose.model('Post', postSchema);
To fetch user information in a post query, use populate:
const Post = require('./post');
Post.find()
.populate('user')
.then(posts => {
console.log(posts);
});
Example of Embedded Relationship
In some cases, embedding subdocuments in the main document allows for faster queries. For example, directly keeping user addresses within the user collection:
const userSchema = new mongoose.Schema({
name: String,
addresses: [{
street: String,
city: String,
zip: String
}]
});
Outcomes of Relation Mapping with Mongoose
With relation mapping with Mongoose, you can both preserve data integrity and easily perform complex queries. Choosing the correct relation mapping type is critical in terms of both performance and your data model. Especially in large projects, it is possible to use both reference and embedded methods together. With tools like populate provided by Mongoose, you can manage relational data operations in MongoDB with ease.

Yorum Gönder