Chuyển đến nội dung

Bài 6 · Models and Entities

Sequelize Models and init()

Define Sequelize models with Model.init and sequelize.define, set tableName, underscored and paranoid options, use getters, setters and virtual fields, with a runnable stand-in.

A Sequelize model is a class that extends Model. You describe its attributes (columns) and options once, and Sequelize adds the static finders (findAll, create, ...) and instance methods (save, destroy, ...). Two styles exist: Model.init() on a class, and the older sequelize.define() shortcut.

Library code is read-only; the stand-ins reproduce the getter, setter and virtual-field behaviour with plain JavaScript.

Model.init

TypeScript
import { DataTypes, Model, InferAttributes, InferCreationAttributes, CreationOptional } from "sequelize";

export class Product extends Model<InferAttributes<Product>, InferCreationAttributes<Product>> {
  declare id: CreationOptional<number>;
  declare title: string;
  declare priceCents: number;
  declare description: string | null;
  declare readonly createdAt: CreationOptional<Date>;
  declare readonly updatedAt: CreationOptional<Date>;
}

Product.init(
  {
    id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true },
    title: { type: DataTypes.STRING(120), allowNull: false },
    priceCents: { type: DataTypes.INTEGER, allowNull: false, field: "price_cents" },
    description: { type: DataTypes.TEXT, allowNull: true },
  },
  {
    sequelize,
    tableName: "products",
    underscored: true,     // createdAt -> created_at
  }
);

The first argument lists attributes; the second holds model options. sequelize (the connection) is required there.

sequelize.define

JavaScript
const Product = sequelize.define(
  "Product",
  {
    title: { type: DataTypes.STRING, allowNull: false },
    priceCents: { type: DataTypes.INTEGER, allowNull: false },
  },
  { tableName: "products" }
);

define returns a model class without you writing the extends. It is concise in JavaScript; TypeScript projects usually prefer Model.init because the class carries the types.

Attributes you will set often

Option Meaning
type A DataTypes.* value
allowNull false creates NOT NULL (default is true)
defaultValue Default in JavaScript and DDL (DataTypes.NOW, DataTypes.UUIDV4 are available)
unique Unique constraint
field Column name in the table
get / set Custom getter and setter
validate Validators (see lesson 5)

Model options worth knowing

Option Effect
tableName Exact table name
freezeTableName Do not pluralize the model name
underscored snake_case column and timestamp names
timestamps false disables createdAt / updatedAt
paranoid destroy() sets deletedAt instead of deleting
defaultScope Filters applied to every query
indexes Index definitions

Getters, setters and virtual fields

A getter changes what you read; a setter changes what is stored; a virtual attribute exists only in JavaScript.

TypeScript
User.init(
  {
    firstName: DataTypes.STRING,
    lastName: DataTypes.STRING,
    email: {
      type: DataTypes.STRING,
      set(value: string) {
        this.setDataValue("email", value.trim().toLowerCase());
      },
    },
    fullName: {
      type: DataTypes.VIRTUAL,
      get() {
        return `${this.getDataValue("firstName")} ${this.getDataValue("lastName")}`;
      },
    },
  },
  { sequelize }
);

Because a virtual field never reaches the database, you cannot use it in a where clause.

Here is the same trio with plain JavaScript property accessors, which is what Sequelize builds under the hood:

Node.js Getter, setter, virtual

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

A mini model factory

init returns a class with finders attached. This stand-in builds that shape on top of node:sqlite, including column renaming through field.

Node.js Mini Model.init

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The last line shows the column really is price_cents, while your code keeps using priceCents.

Common mistakes

  • Using a plain class field (title: string;) instead of declare title: string; in TypeScript. The field initializer overwrites Sequelize's accessor, so reads return undefined.
  • Forgetting sequelize in the options passed to init.
  • Expecting sync() to alter existing tables: by default it only creates missing ones (sync({ alter: true }) changes them, but use migrations for real work).
  • Naming a model Users and then wondering why the table is Userses; use singular model names.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Which Sequelize option makes destroy() set deletedAt instead of removing the row?

    paranoid models are soft-deleted and filtered out of normal queries.
  2. 2. What does a DataTypes.VIRTUAL attribute do?

    Virtual attributes are computed in code; they never reach the database.
  3. 3. Why use declare for TypeScript fields on a Sequelize model?

    A normal class field initializes to undefined and hides the generated getter.
  4. 4. Which attribute option maps priceCents to a price_cents column?

    field sets the column name; underscored: true does it globally.

Summary

  • Models come from Model.init(attributes, options) or sequelize.define().
  • Attributes set type, nullability, defaults, field and validators; options set tableName, underscored, paranoid and more.
  • Getters, setters and virtual fields shape values in JavaScript only.
  • In TypeScript use declare fields, never plain class fields.
  • sync() creates missing tables; migrations handle real schema changes.

Next: Data Types and Column Options

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.