Given the following Sequelize models, what will be the output of console.log(user.posts.length) after fetching the user with posts?
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); }
Remember that hasMany creates an array property on the source model instance when included.
The hasMany association adds a plural property (posts) to the User instance. When you include Post in the query, Sequelize loads all related posts into that array. So user.posts.length gives the count of posts.
Consider these Sequelize models and code snippet. What will be the value of post.userId after creating a post linked to a user?
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); }
Check how belongsTo creates a foreign key field on the source model.
The belongsTo association adds a foreign key field (userId) to the Post model. When creating a post with userId set to the user's id, the value is stored and accessible.
Which option correctly declares a hasMany and belongsTo association between Author and Book models in Sequelize?
const Author = sequelize.define('Author', { name: DataTypes.STRING }); const Book = sequelize.define('Book', { title: DataTypes.STRING });
Check that foreign keys match on both sides of the association.
Option C correctly sets the foreign key authorId on Book for both hasMany and belongsTo. Option C misses explicit foreign keys but is valid if defaults are used. Option C reverses the relationship. Option C mismatches foreign keys.
Given these models and query, why does user.posts return undefined?
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); }
Think about how Sequelize loads associated data.
Sequelize only loads associated data if you specify it in the query using include. Without include: Post, the posts property is not set and remains undefined.
In Sequelize, if you want deleting a User to automatically delete all their Posts, which association option should you use?
Think about which side controls deletion behavior and what 'CASCADE' means.
The onDelete: 'CASCADE' option on hasMany tells Sequelize to delete all related posts when the user is deleted. Other options control update behavior or set foreign keys to null, not cascading deletes.