Bird
Raised Fist0
Expressframework~10 mins

Associations (hasMany, belongsTo) in Express - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Associations (hasMany, belongsTo)
Define Models
Set hasMany on Parent
Set belongsTo on Child
Create Parent Instance
Create Child Instance(s)
Link Child to Parent
Query Parent with Children
Query Child with Parent
Use Associations in Code
This flow shows how to define two models with hasMany and belongsTo associations, create instances, link them, and query related data.
Execution Sample
Express
const User = sequelize.define('User', { name: DataTypes.STRING });
const Post = sequelize.define('Post', { title: DataTypes.STRING });
User.hasMany(Post);
Post.belongsTo(User);
Defines User and Post models, then sets User hasMany Posts and Post belongsTo User associations.
Execution Table
StepActionModel StateAssociation SetResult
1Define User modelUser model createdNoneUser ready
2Define Post modelUser, Post models createdNonePost ready
3User.hasMany(Post)User, Post modelsUser hasMany PostForeign key added to Post
4Post.belongsTo(User)User, Post modelsPost belongsTo UserForeign key confirmed on Post
5Create User instanceUser instance createdAssociations intactUser saved
6Create Post instanceUser instance, Post instance createdAssociations intactPost saved
7Link Post to UserInstances linkedAssociations usedPost.UserId set
8Query User with PostsUser with Posts loadedAssociations usedUser.posts array populated
9Query Post with UserPost with User loadedAssociations usedPost.User object populated
10Use associations in codeData accessible via associationsAssociations usedRelated data available
💡 All steps complete, associations set and used successfully
Variable Tracker
VariableStartAfter Step 5After Step 6After Step 7After Step 8After Step 9Final
UserModelDefinedInstance createdInstance createdInstance createdInstance with postsInstance with postsInstance with posts
PostModelDefinedNot createdInstance createdInstance linkedInstance linkedInstance with userInstance with user
UserInstanceNoneCreatedCreatedCreatedLoaded with postsLoaded with postsLoaded with posts
PostInstanceNoneNoneCreatedLinked to userLinked to userLoaded with userLoaded with user
Post.UserIdUndefinedUndefinedUndefinedSet to User idSet to User idSet to User idSet to User id
Key Moments - 3 Insights
Why do we call hasMany on the parent model and belongsTo on the child model?
hasMany sets up the parent to hold multiple children, while belongsTo sets the child to reference one parent. See execution_table steps 3 and 4 where associations are set.
How does the foreign key get added to the child model?
When hasMany and belongsTo are set, the child model automatically gets a foreign key to link to the parent. This is shown in execution_table step 3 and 4.
How do we access the related data after querying?
After querying with associations, related data is available as properties like user.posts or post.user, as shown in steps 8 and 9.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 7. What happens to Post.userId?
AIt is set to the User instance's id
BIt remains undefined
CIt is deleted
DIt is set to null
💡 Hint
Check the 'Result' column at step 7 in execution_table
At which step do we first create an instance of the Post model?
AStep 5
BStep 6
CStep 3
DStep 8
💡 Hint
Look at the 'Action' column in execution_table for instance creation
If we remove Post.belongsTo(User), what would happen to the foreign key on Post?
AIt would not be added automatically
BIt would be added to User instead
CIt would still be added by hasMany
DIt would cause an error
💡 Hint
Refer to execution_table steps 3 and 4 about foreign key addition
Concept Snapshot
Associations (hasMany, belongsTo) in Express Sequelize:
- Use hasMany on parent to link multiple children
- Use belongsTo on child to link single parent
- belongsTo adds foreign key to child model
- Create instances, then link child.UserId to parent.id
- Query with include to get related data
- Access related data via parent.children or child.parent
Full Transcript
This visual execution trace shows how to set up associations between two models in Express using Sequelize. First, we define two models: User and Post. Then, we set User.hasMany(Post) to indicate one user can have many posts, and Post.belongsTo(User) to indicate each post belongs to one user. These associations add a foreign key to the Post model linking it to User. We create instances of User and Post, then link the post to the user by setting post.UserId. Queries with associations include related data, accessible as user.posts or post.user. This step-by-step trace helps beginners see how associations work in practice.

Practice

(1/5)
1. In Express with Sequelize, what does the hasMany association represent between two models?
easy
A. One model instance can have multiple related instances of another model.
B. One model instance belongs to exactly one instance of another model.
C. Two models have no relationship.
D. Models share the same database table.

Solution

  1. Step 1: Understand the meaning of hasMany

    The hasMany association means one record in a model can be linked to many records in another model.
  2. Step 2: Compare with other associations

    belongsTo means one record belongs to one other record, not many.
  3. Final Answer:

    One model instance can have multiple related instances of another model. -> Option A
  4. Quick 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
A. Comment.belongsTo(Post);
B. Post.belongsTo(Comment);
C. Comment.hasMany(Post);
D. Post.hasMany(Comment);

Solution

  1. Step 1: Identify the direction of belongsTo

    The model that belongs to another calls belongsTo on itself with the other model as argument.
  2. Step 2: Apply to Comment and Post

    Since Comment belongs to Post, the syntax is Comment.belongsTo(Post);.
  3. Final Answer:

    Comment.belongsTo(Post); -> Option A
  4. Quick 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:
Author.hasMany(Book);
Book.belongsTo(Author);

What will await author.getBooks() return if author is an Author instance?
medium
A. An error because belongsTo is missing.
B. An array of Book instances related to that author.
C. Undefined, because getBooks is not a valid method.
D. A single Book instance related to that author.

Solution

  1. 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.
  2. Step 2: Check what getBooks returns

    getBooks returns an array of all Book instances linked to that Author.
  3. Final Answer:

    An array of Book instances related to that author. -> Option B
  4. Quick 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:
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
A. Order should use belongsTo, not hasMany.
B. belongsTo should be called on Order, not Item.
C. Method getItem() is incorrect; should be getItems() because hasMany creates plural getter.
D. findByPk is not a valid Sequelize method.

Solution

  1. Step 1: Identify the association methods

    Order hasMany Item means Sequelize creates getItems() method on Order instances, not getItem().
  2. Step 2: Fix the method call

    Change order.getItem() to order.getItems() to correctly fetch related items.
  3. Final Answer:

    Method getItem() is incorrect; should be getItems() because hasMany creates plural getter. -> Option C
  4. Quick 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
A. User.belongsTo(Profile); Profile.hasOne(User); with user.getProfile() method.
B. User.hasMany(Profile); Profile.belongsTo(User); with user.getProfiles() method.
C. Profile.hasOne(User); User.belongsTo(Profile); with user.getProfile() method.
D. User.hasOne(Profile); Profile.belongsTo(User); with user.getProfile() method.

Solution

  1. Step 1: Identify one-to-one relationship

    Each User has one Profile means hasOne is used, not hasMany.
  2. Step 2: Set belongsTo on Profile

    Profile belongs to User, so Profile.belongsTo(User); is correct.
  3. Step 3: Check available methods

    User instances get getProfile() method for the single related Profile.
  4. Final Answer:

    User.hasOne(Profile); Profile.belongsTo(User); with user.getProfile() method. -> Option D
  5. Quick 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