In this lesson, you will learn how to optimize your application’s performance by deferring the retrieval of related database records until the exact moment your code actually needs them.
The Problem: Over-fetching Data
When using an ORM, it is common to define relationships between models—like a User having many Posts. If you fetch a list of 100 users and your ORM automatically joins and fetches all their posts, you might end up loading thousands of unnecessary records into memory. This "eager" approach consumes memory and slows down your initial query, even if you only planned to display the users' names.
The Solution: Lazy Loading
Lazy loading changes this behavior. Instead of fetching related data immediately, the ORM provides a "proxy" or a placeholder. The database query for the related data is only executed when you specifically access that property in your code.
Think of it like an online shopping cart: the site doesn't load the full details of every item's manufacturing history unless you click "View Details."
A Concrete Illustration
Imagine you have a User model. If you use lazy loading, your code might look like this:
// Fetch the user initially (no posts are loaded yet)
const user = await User.findById(1);
// ... some business logic ...
// The database query for posts happens only here,
// the moment we attempt to access the 'posts' property.
const userPosts = await user.getPosts();
console.log(userPosts);
By waiting to fetch the posts until user.getPosts() is called, you keep your initial User.findById(1) query lightweight and lightning-fast.
When to Use It
Lazy loading is excellent for scenarios where you don't always need the associated data. However, be mindful of the "N+1 problem": if you lazy load associations inside a loop (e.g., fetching posts for every user in a list individually), you will trigger a separate database query for every iteration. In those specific cases, you might prefer a different strategy. For now, focus on lazy loading as your default "on-demand" tool for cleaner, faster data retrieval.
Key Takeaway: Lazy loading optimizes your application by postponing expensive database queries for related records until the moment they are explicitly requested by your code.