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.