Bird
Raised Fist0
Expressframework~20 mins

Associations (hasMany, belongsTo) in Express - Practice Problems & Coding Challenges

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
Challenge - 5 Problems
🎖️
Association Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
Understanding hasMany association behavior

Given the following Sequelize models, what will be the output of console.log(user.posts.length) after fetching the user with posts?

Express
const User = sequelize.define('User', { name: DataTypes.STRING });
const Post = sequelize.define('Post', { title: DataTypes.STRING });
User.hasMany(Post);
Post.belongsTo(User);

async function test() {
  const user = await User.findOne({ where: { id: 1 }, include: [Post] });
  console.log(user.posts.length);
}
AAlways 0, because posts are not loaded automatically
BThe number of posts related to the user (e.g., 3 if user has 3 posts)
CUndefined, because posts is not a property on user
DThrows a runtime error because include is not valid here
Attempts:
2 left
💡 Hint

Remember that hasMany creates an array property on the source model instance when included.

state_output
intermediate
2:00remaining
belongsTo association foreign key value

Consider these Sequelize models and code snippet. What will be the value of post.userId after creating a post linked to a user?

Express
const User = sequelize.define('User', { name: DataTypes.STRING });
const Post = sequelize.define('Post', { title: DataTypes.STRING });
Post.belongsTo(User);
User.hasMany(Post);

async function test() {
  const user = await User.create({ name: 'Alice' });
  const post = await Post.create({ title: 'Hello', userId: user.id });
  console.log(post.userId);
}
AThe id of the user (e.g., 1)
BUndefined, because userId is not set automatically
CNull, because belongsTo does not set foreign keys
DThrows an error because userId is not a defined field
Attempts:
2 left
💡 Hint

Check how belongsTo creates a foreign key field on the source model.

📝 Syntax
advanced
2:00remaining
Correct association declaration syntax

Which option correctly declares a hasMany and belongsTo association between Author and Book models in Sequelize?

Express
const Author = sequelize.define('Author', { name: DataTypes.STRING });
const Book = sequelize.define('Book', { title: DataTypes.STRING });
AAuthor.hasMany(Book); Book.belongsTo(Author);
BAuthor.belongsTo(Book); Book.hasMany(Author);
CAuthor.hasMany(Book, { foreignKey: 'authorId' }); Book.belongsTo(Author, { foreignKey: 'authorId' });
DAuthor.hasMany(Book, { foreignKey: 'bookId' }); Book.belongsTo(Author, { foreignKey: 'authorId' });
Attempts:
2 left
💡 Hint

Check that foreign keys match on both sides of the association.

🔧 Debug
advanced
2:00remaining
Debugging missing association data in query

Given these models and query, why does user.posts return undefined?

Express
const User = sequelize.define('User', { name: DataTypes.STRING });
const Post = sequelize.define('Post', { title: DataTypes.STRING });
User.hasMany(Post);
Post.belongsTo(User);

async function test() {
  const user = await User.findOne({ where: { id: 1 } });
  console.log(user.posts);
}
ABecause the query did not include the Post model, so posts are not loaded
BBecause hasMany association was not declared correctly
CBecause user.posts is always undefined in Sequelize
DBecause the user with id 1 does not exist
Attempts:
2 left
💡 Hint

Think about how Sequelize loads associated data.

🧠 Conceptual
expert
2:00remaining
Understanding cascading deletes with associations

In Sequelize, if you want deleting a User to automatically delete all their Posts, which association option should you use?

APost.belongsTo(User, { onUpdate: 'RESTRICT' });
BUser.hasMany(Post, { onUpdate: 'CASCADE' });
CPost.belongsTo(User, { onDelete: 'SET NULL' });
DUser.hasMany(Post, { onDelete: 'CASCADE' });
Attempts:
2 left
💡 Hint

Think about which side controls deletion behavior and what 'CASCADE' means.

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