Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

667
Vistas
I don't understand this error : "SequelizeEagerLoadingError"

When I test my route with postman I have this error : "SequelizeEagerLoadingError"

I have tried to create an extra-setup for my foreign key because I found this solution (https://forum.freecodecamp.org/t/nodejs-sequelize-eager-loading-error/480312/7) but the problem is similar.

controllers/post.js :

exports.getAllPost = (req, res, next) => {
    /*** on récupère tous les posts ***/
    Post.findAll({
            include: [{
                model: User,
                attributes: ['username']
            }],
        })
        /*** si tout est ok ***/
        .then(post => res.status(200).json({
            post
        }))
        /*** sinon on envoie une erreur ***/
        .catch(error => res.status(400).json({
            error,
        }))

};

models/index.js :

require('dotenv').config();
const dbConfig = require("../config/db.config.js");
const Sequelize = require("sequelize");
const { applyExtraSetup } = require('./extra-setup');

const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
  host: dbConfig.HOST,
  dialect: dbConfig.dialect,
  operatorsAliases: false,
  pool: {
    max: dbConfig.pool.max,
    min: dbConfig.pool.min,
    acquire: dbConfig.pool.acquire,
    idle: dbConfig.pool.idle
  }
});
const db = {};
db.Sequelize = Sequelize;
db.sequelize = sequelize;

db.users = require("./user.js")(sequelize, Sequelize);
db.posts = require("./post.js")(sequelize, Sequelize);
db.comments = require("./comment.js")(sequelize, Sequelize);

applyExtraSetup(sequelize);

module.exports = db;

models/post.js :

module.exports = (sequelize, Sequelize) => {
    const Post = sequelize.define(
      "post", {
        userId: {
          type: Sequelize.INTEGER
        },
        title: {
          type: Sequelize.STRING(40)
        },
      },     
    );
    return Post;
  };

models/extra-setup.js :

function applyExtraSetup(sequelize) {
    const { user, post, comment} = sequelize.models;

      user.hasMany(post, {
        foreignKey : 'userId',
        targetKey: 'id'
      });
      
      post.hasMany(comment, {
        foreignKey : 'postId',
        targetKey: 'id'
      });
      
      user.hasMany(comment, {
        foreignKey : 'userId',
        targetKey: 'id'
      });
}

module.exports = { applyExtraSetup };
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

In order to get posts along with users as an associated models you need define an association from post model to user model:

user.hasMany(post, {
        foreignKey : 'userId',
        targetKey: 'id'
      });
post.belongsTo(user, {
        foreignKey : 'userId',
        targetKey: 'id'
      });
about 4 years ago · Juan Pablo Isaza Denunciar

0

Yes ! it's good !

db.users.hasMany(db.posts, {
  foreignKey : 'userId',
  targetKey: 'id'
});

db.posts.belongsTo(db.users, {
  foreignKey : 'userId',
  targetKey: 'id'
});

db.comments.belongsTo(db.users, {
  foreignKey : 'userId',
  targetKey: 'id'
});

db.comments.belongsTo(db.posts, {
  foreignKey : 'postId',
  targetKey: 'id'
});
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda