'1:N relationship query to find one in Sequelize.js not working properly

I have started learning sequelize.js with node.js and having hard time defining relationships between models. I am trying to create 1:N relationship between users and roles tables i.e. many users can have same role.

Problem

When I query user model to test the defined relation ship it gives me error that original: error: column "RoleId" does not exist.

roles model:

'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class Role extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
      Role.hasMany(models.User, {as: 'users'});
    }
  }
  Role.init({
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
    },
    name:{
      type: DataTypes.STRING,
      allowNull: false
    } 
  }, {
    sequelize,
    modelName: 'Role',
    tableName: 'roles',
  });
  return Role;
};

users model:

'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class User extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
      // User.belongsTo(models.Role, {foreignKey: 'roleId', as: 'role'});
      User.belongsTo(models.Role);
    }
  }
  User.init({
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
    },
    name: {
      type: DataTypes.STRING,
      allowNull: false
    },
    email: {
      type: DataTypes.STRING,
      allowNull: false
    },
    mobile: {
      type: DataTypes.STRING,
      allowNull: false
    }
    // },
    // roleId: {
    //   type: DataTypes.STRING,
    //   allowNull: false
    // }
  }, {
    sequelize,
    tableName: 'users',
    modelName: 'User',
  });
  return User;
};

relationship tester js code:

const { User, Role } = require('./models');

User.findOne({
    where: {email: '[email protected]'}
  })
  .then((findedUser) => {
    console.log(findedUser)
  })
  .catch((err) => {
    console.log("Error while find user : ", err)
  });

Output

Can anyone one please guide me what is wrong with my code?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source