Nodejs Sequelize Eager Loading Error

Hi,

I am trying to create associations between my models , but i keep getting this error:

SequelizeEagerLoadingError

A worker can have many jobs , and a job belongs to one worker.
A client can have any jobs , and a job has one client

I have tried using this method

Model.hasMany(ChildModel, {foreignKey : 'id'}) 

but it also doesnt work.When i use associations i also get an error. If anybody could help me understand what im doing wrong or recommend something i can read i will highly appreciate.

The worker model , the dbconfig contains my connection to the db

const sequelize = require("../dbconfig");
const DataTypes = require('sequelize');
const Joi = require("joi");

const Worker = sequelize.sequelize.define(
  'workers',
  {
    id: {
      autoIncrement: true,
      type: DataTypes.BIGINT,
      allowNull: false,
      primaryKey: true
    },
    username: {
      type: DataTypes.STRING(255),
      allowNull: false
    }
  }, {
  sequelize,
  tableName: 'workers',
  schema: 'public',
  timestamps: false,
  underscored: true,
  indexes: [
    {
      name: "worker_profiles_pkey",
      unique: true,
      fields: [
        { name: "id" },
      ]
    },
  ]
}
);

function validateWorker(Worker) {
  const schema = Joi.object({
    username: Joi.string()
      .min(3)
      .max(191)
      .required()
  });

  return schema.validate(Worker);
}

Worker.associate = function(models) {
  Worker.hasMany(models.Job, { 
      foreignKey : "worker_id",
      as: 'jobs' 
  });
}

Worker.associate = function(models) {
  Worker.belongsTo(models.User, { 
      foreignKey : "user_id",
      sourceKey : 'id' 
  });
}

exports.Worker = Worker;
exports.validateWorker = validateWorker;


My job model looks like this :

const sequelize = require("../dbconfig");
const DataTypes = require("sequelize");
const Joi = require("joi");

const Job = sequelize.sequelize.define(
  'jobs',
  {
    id: {
      autoIncrement: true,
      type: DataTypes.BIGINT,
      allowNull: false,
      primaryKey: true
    },
    worker_id: {
      type: DataTypes.BIGINT,
      allowNull: true,
      references: {
        model: 'workers',
        key: 'id'
      }
    },
  }, {
  sequelize,
  tableName: 'jobs',
  schema: 'public',
  timestamps: false,
  underscored: true,
  indexes: [
    {
      name: "jobs_pkey",
      unique: true,
      fields: [
        { name: "id" },
      ]
    },
  ]
}
);

function validateJob(job) {
  const schema = Joi.object({
    title: Joi.string()
      .min(3)
      .max(191)
      .required(),
    worker_id: Joi.number(),
  }).unknown(true);

  return schema.validate(job);
};

Job.associate = function(models) {
  Job.belongsTo(models.Worker, { 
      foreignKey : "worker_id",
      as : 'worker' 
  });
}

module.exports.Job = Job;
exports.validateJob = validateJob;

1 Like

Hello!

In case you don’t know, Eager Loading means the data is read from the database when the model is instantiated. On the other hand, Lazy Loading means the data is read from the database when required (or the model is accessed). The concept of eager/lazy loading is not exclusive to databases (or ORMs).

This problem usually means you’re accessing a Model when there’s no database access (for instance, before the connection to the database was established or once it’s been closed), but without the whole error or the code, I’m unable to see the problem.

If I have to guess, I would say the problem lies in how you’re connecting to the database and then defining your models, but I’m not sure.

Thanks @skaparate , this is how i access my database :slight_smile:

const sequelize = new Sequelize(database, username, password, {
	host: db_server,
	port: port,
	dialect: "postgres",
});

const connect = async () => {
	await sequelize
		.authenticate()
		.then(() => {
			console.log("Connection has been established successfully.");
		})
		.catch((err) => {
			console.log("Unable to connect to the database:", err.message);
		});
};
const db = {
	sequelize: sequelize,
	connect,
};

module.exports = db;

And im accessing the data like this :

let workers = await Worker.findAll({
            include: [{ model: User, attributes: { exclude: ['password'] },
                        model : Job , as: 'jobs', }],
        })

And where do you actually connect (where do you call db.connect())?

Here : const sequelize = require("…/dbconfig");

Hmmm, is SequelizeEagerLoadingError the only thing that gets displayed when the error occurs?

Could you setup a repl.it with the code you have now?

My repl : Sign Up - Replit

It also contains my db structure in the db.sql file

yes, the only error that comes is SequelizeEagerLoadingError

Ok, I’m not entirely sure about the problem, but I believe it’s related to how the models are being included. As stated on the sequelize docs:

Which means you cannot include a required association after it’s defined.

A better approach may be to define everything in one place and later create the associations. Take a look at this example using express.

As shown in the example, you can create your models separately and later add the associations, passing a reference to the sequelize object.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.