MongoDB - Model relationships between documents in MongoDB
In MongoDB, there is no direct concept of foreign keys as you would find in traditional relational databases like MySQL or PostgreSQL. MongoDB is a NoSQL database, and it follows a document-oriented data model, which means it doesn't have a strict schema or support for relationships like foreign keys.
However, you can still model relationships between documents in MongoDB using a technique called "manual referencing" or "embedding."
1. Manual Referencing: With manual referencing, you create a separate collection for related documents and store references to those documents in the main document using their _id field. This is similar to using foreign keys in traditional databases.
Let's say you have two collections, users and posts, and you want to establish a one-to-many relationship where each post is associated with a user:
// User schem
const userSchema = new mongoose.Schema({
name: String,
email: String,
});
// Post schema
const postSchema = new mongoose.Schema({
title: String,
content: String,
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' } // Reference to the User collection
});
const User = mongoose.model('User', userSchema);
const Post = mongoose.model('Post', postSchema);a
In this example, the author field in the Post schema is set as a reference to the User collection. When you create a new post, you can set the author field to the _id of the user who created the post.
Recommended by LinkedIn
// Create a new use
const newUser = new User({
name: 'John Doe',
email: 'john@example.com',
});
await newUser.save();
// Create a new post and link it to the user using manual referencing
const newPost = new Post({
title: 'My First Post',
content: 'This is my first blog post.',
author: newUser._id, // Set the author field with the user's _id
});
await newPost.save();
2. Embedding: Alternatively, you can embed related data directly within the document. In the case of one-to-many relationships, you can embed an array of subdocuments inside the main document.
// User schema
const userSchema = new mongoose.Schema({
name: String,
email: String,
posts: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Post' }]
});
// Post schema
const postSchema = new mongoose.Schema({
title: String,
content: String,
});
const User = mongoose.model('User', userSchema);
const Post = mongoose.model('Post', postSchema);
In this approach, each user document will have an array of post references, and each post document will have its data along with an author field containing the user's _id.
// Create a new use
const newUser = new User({
name: 'John Doe',
email: 'john@example.com',
});
await newUser.save();
// Create a new post and embed it within the user document
const newPost = new Post({
title: 'My First Post',
content: 'This is my first blog post.',
});
await newPost.save();
// Add the post's _id to the user's posts array
newUser.posts.push(newPost._id);
await newUser.save();
Both manual referencing and embedding have their pros and cons, and the choice depends on your specific use case and query patterns. Manual referencing allows for more flexibility when querying and managing relationships while embedding can be more efficient for certain types of queries but may lead to document size and update complexity considerations.