I have an error with Sequelize model.
I have two models: Hostel and Faculty. And I need many-to-many relationship between them.
I added to Hostel the next:
Hostel.belongsToMany(Faculty, {
through: 'university.hostels_to_faculties',
sourceKey: 'hostel_id',
targetKey: 'faculty_id',
onUpdate: 'CASCADE',
onDelete: 'CASCADE'
});
Full code source is here: https://github.com/ASUDR/backend/blob/dev/src/db/models/university/Hostel.ts#L41
And when I run this code, I get an error:
/opt/app/node_modules/sequelize/lib/associations/belongs-to-many.js:129 this.sourceKeyField = this.source.rawAttributes[this.sourceKey].field || this.sourceKey;
(here is arrow that points out to field at this.source.rawAttributes[this.sourceKey].field)
TypeError: Cannot read properties of undefined (reading 'field') at new BelongsToMany (/opt/app/node_modules/sequelize/lib/associations/belongs-to-many.js:129:69) at Function.belongsToMany (/opt/app/node_modules/sequelize/lib/associations/mixin.js:64:25) at file:///opt/app/dist/db/models/university/Hostel.js:24:8 at ModuleJob.run (node:internal/modules/esm/module_job:183:25) at async Loader.import (node:internal/modules/esm/loader:178:24) at async Object.loadESM (node:internal/process/esm_loader:68:5) at async handleMainPromise (node:internal/modules/run_main:63:12)
I fixed this error by creating the model for junction table:
import Sequelize, { Optional } from 'sequelize';
import sequelize from '../../sequelize';
const { DataTypes, Model } = Sequelize;
export interface FacultyHostelsAttributes {
id: number;
hostelId: number;
facultyId: number;
}
export interface FacultyHostelsAttributesInput extends Optional<FacultyHostelsAttributes, 'id'> {}
export interface FacultyHostelsAttributesOutput extends Required<FacultyHostelsAttributes> {}
export class FacultyHostels
extends Model<FacultyHostelsAttributes, FacultyHostelsAttributesInput>
implements FacultyHostelsAttributes {
public id: number;
public hostelId: number;
public facultyId: number;
}
FacultyHostels.init({
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
hostelId: {
type: DataTypes.INTEGER,
field: 'hostel_id',
allowNull: false
},
facultyId: {
type: DataTypes.INTEGER,
field: 'faculty_id',
allowNull: false
}
}, {
sequelize,
schema: 'objects',
modelName: 'faculty_hostels',
timestamps: false
});
And changing belongsToMany arguments:
Hostel.belongsToMany(Faculty, {
through: FacultyHostels,
onUpdate: 'CASCADE',
onDelete: 'CASCADE'
});
Faculty.belongsToMany(Hostel, {
through: FacultyHostels,
onUpdate: 'CASCADE',
onDelete: 'CASCADE'
});
more: https://github.com/ASUDR/backend/blob/main/src/db/models/university/Hostel.ts