Associations help connect data models so they can work together. They show how one item relates to many others or belongs to one.
Associations (hasMany, belongsTo) in Express
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Express
ModelA.hasMany(ModelB, { foreignKey: 'modelAId' });
ModelB.belongsTo(ModelA, { foreignKey: 'modelAId' });hasMany means one item in ModelA can have many items in ModelB.
belongsTo means each item in ModelB belongs to one item in ModelA.
Examples
Express
User.hasMany(Post, { foreignKey: 'userId' });
Post.belongsTo(User, { foreignKey: 'userId' });Express
Category.hasMany(Product, { foreignKey: 'categoryId' });
Product.belongsTo(Category, { foreignKey: 'categoryId' });Sample Program
This example creates a User and two Posts linked to that user. Then it fetches all posts for the user and prints their titles.
Express
import express from 'express'; import { Sequelize, DataTypes } from 'sequelize'; const app = express(); const sequelize = new Sequelize('sqlite::memory:'); const User = sequelize.define('User', { name: DataTypes.STRING }); const Post = sequelize.define('Post', { title: DataTypes.STRING, content: DataTypes.TEXT, userId: DataTypes.INTEGER }); // Define associations User.hasMany(Post, { foreignKey: 'userId' }); Post.belongsTo(User, { foreignKey: 'userId' }); async function setup() { await sequelize.sync({ force: true }); const user = await User.create({ name: 'Alice' }); await Post.create({ title: 'Hello', content: 'First post', userId: user.id }); await Post.create({ title: 'World', content: 'Second post', userId: user.id }); const posts = await user.getPosts(); posts.forEach(post => { console.log(`${user.name} wrote: ${post.title}`); }); } setup();
Important Notes
Always define both sides of the association for clarity and easier queries.
Use the same foreign key name in both hasMany and belongsTo to link models correctly.
Sequelize automatically adds helper methods like getPosts() when associations are set.
Summary
Associations connect models to show relationships.
hasMany means one item has many related items.
belongsTo means one item belongs to another single item.
Practice
1. In Express with Sequelize, what does the
hasMany association represent between two models?easy
Solution
Step 1: Understand the meaning of hasMany
ThehasManyassociation means one record in a model can be linked to many records in another model.Step 2: Compare with other associations
belongsTomeans one record belongs to one other record, not many.Final Answer:
One model instance can have multiple related instances of another model. -> Option AQuick Check:
hasMany = one-to-many [OK]
Hint: hasMany means one item links to many others [OK]
Common Mistakes:
- Confusing hasMany with belongsTo
- Thinking hasMany means no relation
- Assuming hasMany means shared tables
2. Which of the following is the correct syntax to define a belongsTo association in Sequelize for a model
Comment that belongs to Post?easy
Solution
Step 1: Identify the direction of belongsTo
The model that belongs to another callsbelongsToon itself with the other model as argument.Step 2: Apply to Comment and Post
Since Comment belongs to Post, the syntax isComment.belongsTo(Post);.Final Answer:
Comment.belongsTo(Post); -> Option AQuick Check:
belongsTo called on child model [OK]
Hint: belongsTo called on the model that belongs [OK]
Common Mistakes:
- Reversing the models in belongsTo
- Using hasMany instead of belongsTo
- Calling belongsTo on the wrong model
3. Given the following Sequelize association code:
What will
Author.hasMany(Book); Book.belongsTo(Author);
What will
await author.getBooks() return if author is an Author instance?medium
Solution
Step 1: Understand hasMany and belongsTo setup
Author has many Books, and each Book belongs to one Author, so Sequelize creates methods like getBooks on Author instances.Step 2: Check what getBooks returns
getBooks returns an array of all Book instances linked to that Author.Final Answer:
An array of Book instances related to that author. -> Option BQuick Check:
hasMany creates plural get method returning array [OK]
Hint: hasMany creates getPlural() returning array [OK]
Common Mistakes:
- Expecting a single instance instead of array
- Thinking getBooks is invalid method
- Ignoring belongsTo association
4. Consider this Sequelize association code with an error:
What is the error and how to fix it?
Order.hasMany(Item); Item.belongsTo(Order); // Later in code const order = await Order.findByPk(1); const items = await order.getItem();
What is the error and how to fix it?
medium
Solution
Step 1: Identify the association methods
Order hasMany Item means Sequelize creates getItems() method on Order instances, not getItem().Step 2: Fix the method call
Changeorder.getItem()toorder.getItems()to correctly fetch related items.Final Answer:
Method getItem() is incorrect; should be getItems() because hasMany creates plural getter. -> Option CQuick Check:
hasMany creates plural get method [OK]
Hint: hasMany creates plural get method, use getItems() [OK]
Common Mistakes:
- Using singular get method for hasMany
- Confusing belongsTo direction
- Thinking findByPk is invalid
5. You have two models:
User and Profile. Each User has one Profile, and each Profile belongs to one User. Which Sequelize associations correctly represent this, and what methods will be available on User instances?hard
Solution
Step 1: Identify one-to-one relationship
Each User has one Profile meanshasOneis used, nothasMany.Step 2: Set belongsTo on Profile
Profile belongs to User, soProfile.belongsTo(User);is correct.Step 3: Check available methods
User instances getgetProfile()method for the single related Profile.Final Answer:
User.hasOne(Profile); Profile.belongsTo(User); with user.getProfile() method. -> Option DQuick Check:
One-to-one uses hasOne + belongsTo [OK]
Hint: One-to-one uses hasOne + belongsTo with singular get method [OK]
Common Mistakes:
- Using hasMany for one-to-one
- Reversing belongsTo direction
- Expecting plural get method for one-to-one
