Skill for defining, registering, and managing Sequelize ORM models to ensure database consistency.
Follow this guide to professionally add and register new database models in the project.
Create a new file in model/YourModel.ts. Use the functional define pattern (No Classes).
import { DataTypes, Model, Optional } from "sequelize";
import { sequelize } from "../utils/db";
export interface YourModelAttributes {
id: number;
name: string;
// ...
createdAt?: Date;
updatedAt?: Date;
}
export type YourModelCreationAttributes = Optional<YourModelAttributes, "id">;
export const YourModel = sequelize.define<Model<YourModelAttributes, YourModelCreationAttributes>>(
"your_model_table_name",
{
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},
// ...
}
);
After defining your model, you MUST register it in utils/db.ts within the syncDB function. This ensures that the model is loaded into memory before the database syncs.
utils/db.ts.syncDB function.// utils/db.ts
export const syncDB = async (force = false) => {
// ...
syncPromise = (async () => {
try {
await import("../model/User");
await import("../model/Post");
await import("../model/YourNewModel"); // <--- Add this!
// ...
By default, alter is set to false in syncDB to prevent index bloat. If you add a new column or table:
alter: false to alter: true in utils/db.ts.alter: false to protect the database.If you see "Table 'table_name' doesn't exist", double check that:
syncDB.syncDB() or ensureDbInitialized() is called at the top of your API route or service.