ammezie
ammezie

Reputation: 355

Sequelize relation helper method returning null immediately after insertion

I'm currently experiencing a weird issue with my code regarding sequelize association. I have the following relationships defined:

Recipe.associate = function (models) {
    Recipe.belongsTo(models.User)
}

User.associate = function (models) {
    User.hasMany(models.Recipe)
}

I can get the related model using recipe.getUser() only if a retrieve the recipe with Recipe.findById(id). But if I try doing recipe.getUser() immediately after inserting a recipe using:

const recipe = await Recipe.create({ userId, title, ingredients, direction})
const user = await recipe.getUser()
console.log(user)

This returns null, which I can't wrap my head around why it's so.

Upvotes: 0

Views: 637

Answers (2)

ammezie
ammezie

Reputation: 355

I resolved it. Seauelize does some magic underneath with it naming convention. So in my case, it's looking for a UserId (since I define my model as User) column on my Recipe model, of which I have defined as userId. So all I need to do is explicitly specify the correct column while defining the association:

Recipe.belongsTo(models.User, { foreignKey: 'userId' })

I have to put it out here in case someone else ever gets stuck with this issue.

Upvotes: 1

Stephen R. Smith
Stephen R. Smith

Reputation: 3400

My guess would be that the console.log(user) is executing before the user is getting the response back from recipe.getUser().

Maybe try this:

const recipe = await Recipe.create({ userId, title, ingredients, direction})
const user = await recipe.getUser()
.then(data => {
    console.log(data);
});

Upvotes: 0

Related Questions