reactjssequelize.js

Roles not associated to Users


I am trying to use react with sequelize woth mysql. I have 3 modules, Users, Roles and User_Roles. I thought I have the association correctly setup, but when running the code it says: Roles not associated to Users.

Here is my setup:

Users.js

module.exports = (sequelize, DataTypes) => {

    const Users = sequelize.define("Users", {
        user_fname: {
            type: DataTypes.STRING,
            allowNull: false,
        },
        user_mname: {
            type: DataTypes.STRING,
            allowNull: true,
        },
        user_sname: {
            type: DataTypes.STRING,
            allowNull: false,
        },
        user_fullname: {
            type: DataTypes.STRING,
            allowNull: false,
        },
        user_email: {
            type: DataTypes.STRING,
            allowNull: false,
        },
        user_pass: {
            type: DataTypes.TEXT,
            allowNull: false,
        },
    });

    Users.associate = (models) => {
        Users.hasMany(models.User_Roles);
    };

    return Users;
};

Roles.js:

module.exports = (sequelize, DataTypes) => {

    const Roles = sequelize.define("Roles", {
        roleName: {
            type: DataTypes.STRING,
            allowNull: false,
        },
    });

    Roles.associate = (models) => {
        Roles.hasMany(models.User_Roles);
    }

    return Roles;
}

User_Roles.js

module.exports = (sequelize, DataTypes) => {

    const UserRoles = sequelize.define("User_Roles");

    return UserRoles;
}

User.js // Routes

const express = require("express");
const router = express.Router();
const { Users, Roles } = require("../models");

router.get("/", async (req, res) => {
    const listOfUsers = await Users.findAll({ include: [Roles] });
    res.json({ listOfUsers: listOfUsers });
});

router.get("/byId/:id", async (req, res) => {
    const id = req.params.id;
    const user = await Users.findByPk(id);
    res.json(user);
});

router.post("/", async (req, res) => {
    const user = req.body;
    await Users.create(user);
    res.json(user);
});

module.exports = router;

In the table: User_Roles, there are already 2 columns: UserId and RoleId, so I am unsure why I get that error message.


Solution

  • Oh stupid me, I had to update the following lines:

    const { Users, Roles } = require("../models");
    
    const listOfUsers = await Users.findAll({ include: [Roles] });
    

    It had to be:

    const { Users, User_Roles } = require("../models");
    
    const listOfUsers = await Users.findAll({ include: [User_Roles] });
    

    This fixed the issue.