Discover how simple connections between data models can save you hours of confusing code!
Why Associations (hasMany, belongsTo) in Express? - Purpose & Use Cases
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.
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.
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.
const authorBooks = books.filter(book => book.authorId === author.id);
Author.hasMany(Book); Book.belongsTo(Author); const authorBooks = await author.getBooks();
It enables simple, reliable access to related data, making your code cleaner and your app faster.
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.
Manual data linking is slow and error-prone.
Associations define clear, automatic relationships between models.
This makes data fetching easier, cleaner, and more reliable.