0
0
Expressframework~3 mins

Why Associations (hasMany, belongsTo) in Express? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how simple connections between data models can save you hours of confusing code!

The Scenario

Imagine you have two lists: one for authors and one for books. You want to connect each book to its author manually by searching through both lists every time you need to find related data.

The Problem

Manually linking data like this is slow and confusing. You might forget to update both lists, causing errors. It's hard to keep track of which books belong to which authors, especially as data grows.

The Solution

Associations like hasMany and belongsTo let you define clear relationships between data models. This way, you can easily fetch all books for an author or find the author of a book without messy manual code.

Before vs After
Before
const authorBooks = books.filter(book => book.authorId === author.id);
After
Author.hasMany(Book);
Book.belongsTo(Author);
const authorBooks = await author.getBooks();
What It Enables

It enables simple, reliable access to related data, making your code cleaner and your app faster.

Real Life Example

Think of a blog where each post belongs to a user. Using associations, you can quickly show all posts by a user or find who wrote a post without extra searching.

Key Takeaways

Manual data linking is slow and error-prone.

Associations define clear, automatic relationships between models.

This makes data fetching easier, cleaner, and more reliable.