Wednesday 29 April 2020

getting {} as response to http req due to bad associations

I have two tables://User.js module.exports = (sequelize, DataTypes) => { const User = sequelize.define("User", { userId: { type: DataTypes.STRING, allowNull: false, unique: true, primaryKey: true, }, email: { type: DataTypes.STRING, }, firstName: { type: DataTypes.STRING, allowNull: false, }, lastName: { type: DataTypes.STRING, defaultValue: "", }, password: { type: DataTypes.STRING, allowNull: false, }, chapterId: { type: DataTypes.STRING, }, }); User.associate = (models) => { User.belongsTo(models.Chapter, { foreignKey: "chapterId", targetKey: "chapterId", as: "chapter", }); }; return User; }; and//chapter table module.exports = (sequelize, DataTypes) => { const Chapter = sequelize.define("Chapter", { chapterId: { type: DataTypes.STRING, allowNull: false, unique: true, primaryKey: true, }, chapterName: { type: DataTypes.STRING, allowNull: false, }, isChapterLocal: { type: DataTypes.BOOLEAN, allowNull: false, }, }); Chapter.associate = (models) => { }; return Chapter; }; and i am trying to fetch users with chapters included into it based on chapterId.let getAll = async (req, res) => { try { const userData = await db.User.findAll({ include: [ { model: Chapter, as: "chapter", }, ], }); res.send(userData); } catch (e) { res.send(e); } }; feels like my associations are the problem.how to include chapter id and chapter name from chapter table, as present in chapterId row for user table. I am new to sequelize and MySQL and am unsure if the relation i have defined in the user model is good. Do we need to define associations in both tables.HELP!!

Submitted April 30, 2020 at 06:07AM by meMindFlayer

No comments:

Post a Comment