In this lesson, you will learn how to improve your application's performance by embedding child entities directly inside a parent document to enable faster data retrieval.
The Problem with Normalization
In relational databases, we are taught to keep data in separate tables. For example, if you have a User and their Addresses, you might store them in two tables and perform a JOIN to retrieve them together. While this keeps data clean, it forces the database to perform multiple lookups every time you fetch a user, which can slow down your Node.js application as your traffic grows.
The Embedding Strategy
In document-oriented databases, we can optimize for "read-heavy" workloads by storing hierarchical data—where the parent and child are tightly coupled—as a single document. Instead of linking entities by ID, you physically nest the child data inside the parent object.
Consider a Customer profile that needs to display their saved addresses. By embedding the addresses directly into the customer document, you can retrieve both in a single database round-trip without needing any joins:
// A single document in your database
const customer = {
_id: "user_123",
name: "Jane Doe",
addresses: [
{ type: "home", street: "123 Maple St", city: "Nodeville" },
{ type: "work", street: "456 Script Ave", city: "Backend City" }
]
};
Why this is faster
When you perform a db.customers.findOne({ _id: "user_123" }), the database returns the entire object, including the addresses, immediately. This avoids the overhead of managing complex relationship lookups at the application level.
However, keep in mind that this approach is best suited for data that is almost always accessed together. If your child entities (like these addresses) rarely change and are primarily read alongside the parent, embedding is a powerful way to reduce latency and simplify your data access logic in Node.js.
Key Takeaway: By embedding hierarchical child data directly into the parent document, you eliminate the need for costly joins and speed up data retrieval by fetching everything in a single query.