eager loading issue when calling getAll() function #16880
Unanswered
Kendyelisca
asked this question in
Help & Questions
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I have already established all the relationship logic but I am getting this error:
Error fetching stories: EagerLoadingError [SequelizeEagerLoadingError]: comment is not associated to story!
at story._getIncludedAssociation (C:\Users\kendy\Daily-personal-projects\newsFlow-backend\node_modules\sequelize\lib\model.js:565:13)
here's the function:
const getAll = catchError(async (req, res) => {
try {
const results = await Story.findAll({
include: [
{ model: User, attributes: ["id", "name", "username", "email"] },
{ model: Comment, attributes: ["id", "text", "UserId"] },
],
});
} catch (error) {
console.error("Error fetching stories:", error);
}
});
but I have already take the necessary steps to established the relationship like follows:
const Comment = require("./Comment");
const Save = require("./Save");
const Story = require("./Story");
const User = require("./User");
User.hasMany(Save);
Save.belongsTo(User);
User.hasMany(Story);
Story.belongsTo(User);
User.hasMany(Comment);
Comment.belongsTo(User);
Comment.belongsTo(Story, { foreignKey: "commentId" });
Story.hasMany(Comment, { foreignKey: "storyId" });
I wonder if the error occurs because the comment belongs to both the User and the Story or a problem with sequelize not supporting the relationship how I have defined it! Well I would really appreciate your help on this. Thanks!
Beta Was this translation helpful? Give feedback.
All reactions