I am using Sequelize with TypeScript in Node.js. My question is how to spread sequelize models into different files and import them afterwards into one. Maybe an example:
database.ts
import { Sequelize, DataTypes, Model, Op } from 'sequelize'
import constants from "../../utils/constants"
//create connection
const sequelize = new Sequelize(constants.DATABASE, constants.USERNAME, constants.PASSWORD, {
host: constants.HOST,
dialect: 'mysql',
dialectOptions: {
connectTimeout: 10000
},
port: constants.DBPORT,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000,
}
});
sequelize.authenticate().catch(err => {
console.error("err: ", err)
});
export { sequelize }
userModel.ts
import { sequelize } from "./model"
import { DataTypes, Model } from 'sequelize'
interface UserAttributes {
ID: number,
EMail: string;
Password: string;
Balance: number;
}
interface UserInstance extends Model<UserAttributes>, UserAttributes {}
const User = sequelize.define<UserInstance>("User", {
ID: {
type: DataTypes.INTEGER,
unique: true,
autoIncrement: true,
primaryKey: true,
},
EMail: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
Password: {
type: DataTypes.STRING,
allowNull: false,
},
Balance: {
type: DataTypes.DOUBLE,
allowNull: false,
},
},
{
timestamps: false,
createdAt: false,
updatedAt: false,
freezeTableName: true,
},
);
export {
User,
UserInstance
}
what if i have models referencing to that model? like
import { sequelize } from "./model"
import { DataTypes, Model } from 'sequelize'
import { User } from "./userModel"
import { Stock } from "./stockModel"
interface TransactionAttributes {
TID: number
PriceAtAquisition: number
TransactionQuantity: number
Date: Date
UID: number
SISIN: string
}
interface TransactionInstance extends Model<TransactionAttributes>, TransactionAttributes {}
const Transaction = sequelize.define<TransactionInstance>("Transaction", {
TID: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
unique: true,
},
PriceAtAquisition: {
type: DataTypes.DOUBLE,
allowNull: false,
},
TransactionQuantity: {
type: DataTypes.INTEGER,
allowNull: false,
},
Date: {
type: DataTypes.DATE,
allowNull: false,
},
UID:{
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: User,
key: 'ID'
}
},
SISIN: {
type: DataTypes.STRING,
allowNull: false,
references: {
model: Stock,
key: 'ISIN'
}
},
},
{
timestamps: false,
createdAt: false,
updatedAt: false,
freezeTableName: true,
},
);
export {
Transaction,
TransactionInstance
}
i get the error this if i try to run with nodemon:
const User = sequelize.define<UserInstance>("User", {
^
TypeError: Cannot read properties of undefined (reading 'define')
I looked up on the internet but found nothing useful for my case
New contributor
Eray Kirkic is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.