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 };
CodePudding user response:
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'
});
CodePudding user response:
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'
});