Unable to create association with Sequelize

Question

I'm using sequelize for my project and trying to create a simple association between two models.

User model:

`const { DataTypes } = require('sequelize');
import db from '../db';

const UserModel = db.define('user', {
  id: {
    type: DataTypes.STRING,
    unique: true,
    primaryKey: true,
    allowNull: false
  },
  email: {
    type: DataTypes.STRING,
    allowNull: true,
    unique: true
  },
  ...
});

export default UserModel;`

Session model

`const { DataTypes } = require('sequelize');
import db from '../db';

const SessionModel = db.define('session', {
  id: {
    type: DataTypes.STRING,
    unique: true,
    allowNull: false,
    primaryKey: true
  },
  userId: {
    type: DataTypes.STRING,
    allowNull: false,
    references: {
      model: 'users',
      key: 'id'
    }
  },
  expiresAt: {
    type: DataTypes.DATE,
    allowNull: false
  }
});

export default SessionModel;`

I have a script for migration, and here is how i define association

`require('dotenv').config({ path: '../.env' });
const { DataTypes } = require('sequelize');

import db from '../db';

// Models
import SessionModel from '../models/session';
import UserModel from '../models/user';

/**
 * Associations.
 */

// Session - User association
UserModel.hasMany(SessionModel, { foreignKey: 'userId', type: DataTypes.STRING });
SessionModel.belongsTo(UserModel, { foreignKey: 'userId', type: DataTypes.STRING });

/**
 * Sync the database.
 */
const start = async () => {
  await db.sync({ force: true });
};

if (process.env.START && require.main === module) {
  start()
    .then(() => {
      console.info('DONE ✨');
    })
    .catch((err) => {
      console.error('ERROR 💥', err);
    });
}`

Then I try to retrieve user data with session like this

`const users = await UserModel.findAll({
    where: whereCondition,
    include: [SessionModel]
  });`

The error message is "session is not associated to user!"

Sequelize version is

`"sequelize": "^6.35.1"`

Answer

Your associations seem to be set up correctly and the issue might be coming from the way you are referencing your models, specifically in the code below:

`userId: {
    type: DataTypes.STRING,
    allowNull: false,
    references: {
      model: 'users',
      key: 'id'
    }
  },`

This answer was originally posted on Stack Overflow. You can find the full discussion here.

Related Posts

Transfer git repositories from GitLab to GitHub - can we, how to and pitfalls (if any)?

## Question Can one transfer repositories from GitLab to GitHub if the need be. If so, how exactly can I go about doing the same? Also, are there any pitfalls in doing so or precautionary measures

Read More

Cannot set headers after they are sent to the client - error

## Question Error `[ERR_HTTP_HEADERS_SENT]`: Cannot set headers after they are sent to the client ```text `at ServerResponse.setHeader (_http_outgoing.js:558:11) at ServerResponse.header (D:\D

Read More

Pulling data with 'Where' and 'Include' statements at the same time

## Question I have managed to get my include statements working with my foreign keys however when I try to add a 'where' statement to the findAll statement I am getting the below error. I have check

Read More