Performance: Associations (hasMany, belongsTo)
This affects how many database queries and data processing happen during page load and user interactions.
Jump into concepts and practice - no test required
const posts = await Post.findAll({ include: [{ model: User, as: 'author' }] }); res.json(posts);
const posts = await Post.findAll(); for (const post of posts) { post.author = await User.findByPk(post.userId); } res.json(posts);
| Pattern | Database Queries | Response Time | Server Load | Verdict |
|---|---|---|---|---|
| Lazy loading associations (N+1 queries) | N+1 queries | High | High | [X] Bad |
| Eager loading associations (single query) | 1 query | Low | Low | [OK] Good |
hasMany association represent between two models?hasMany association means one record in a model can be linked to many records in another model.belongsTo means one record belongs to one other record, not many.Comment that belongs to Post?belongsTo on itself with the other model as argument.Comment.belongsTo(Post);.Author.hasMany(Book); Book.belongsTo(Author);
await author.getBooks() return if author is an Author instance?Order.hasMany(Item); Item.belongsTo(Order); // Later in code const order = await Order.findByPk(1); const items = await order.getItem();
order.getItem() to order.getItems() to correctly fetch related items.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?hasOne is used, not hasMany.Profile.belongsTo(User); is correct.getProfile() method for the single related Profile.