0

I have this error and can`t find a way arround it: EagerLoadingError [SequelizeEagerLoadingError]: users is not associated to blog! using node and sequelize

User model

import { Sequelize } from "sequelize"; 
import db from "../config/Database.js"; 
import Blogs from "./BlogModel.js";   
const { DataTypes } = Sequelize;   
const Users = db.define('users',{
    id:{
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    name:{
        type: DataTypes.STRING
    },
    email:{
        type: DataTypes.STRING
    },
    password:{
        type: DataTypes.STRING
    },
    refresh_token:{
        type: DataTypes.TEXT
    }, }); Users.associate = function() {
    Users.hasMany(Blogs, {
        foreignKey: 'created_by'
    }); 
} 
export default Users;

Blog model

import { Sequelize } from "sequelize";
import db from "../config/Database.js";
import Users from "./UserModel.js";
 
const { DataTypes } = Sequelize;
 
const Blogs = db.define('blog',{
    id:{
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    title:{
        type: DataTypes.STRING
    },
    content:{
        type: DataTypes.TEXT
    },
    created_by:{
        type: DataTypes.STRING,
    },
});
Blogs.associate = function() {
    Blogs.belongsTo(Users, {
        foreignKey: 'created_by'
    })
}
 
export default Blogs;

I keep getting the error 'users is not associated to blog'. Can you please guide me where I am making the mistake?

Doyino Delima
  • 33
  • 1
  • 5

1 Answers1

0

You need to register all associations after all models will be registered. See my other answer to get an idea how to do it.

Anatoly
  • 20,799
  • 3
  • 28
  • 42