Skip to content

Models and data types ​

Models work as in Sequelize v6: extend Model and call init, or use sequelize.define. Both forms accept the same attribute and model options.

Class models ​

Declare attributes with declare so TypeScript knows their types without emitting class fields that would shadow the attribute getters. InferAttributes<T> collects the declared fields; InferCreationAttributes<T> additionally makes CreationOptional fields optional in create and build.

ts
class Product extends Model<InferAttributes<Product>, InferCreationAttributes<Product>> {
  declare id: CreationOptional<number>;
  declare sku: string;
  declare name: string;
  declare tags: CreationOptional<string[]>;
  declare attrs: CreationOptional<Record<string, unknown>>;
  declare status: CreationOptional<'draft' | 'live'>;
  declare label: CreationOptional<string>;
}

Product.init(
  {
    id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
    sku: {
      type: DataTypes.STRING(32),
      allowNull: false,
      unique: true,
      set(this: Product, value: string) {
        this.setDataValue('sku', value.toUpperCase());
      },
    },
    name: { type: DataTypes.TEXT, allowNull: false },
    tags: { type: DataTypes.ARRAY(DataTypes.TEXT), allowNull: false, defaultValue: [] },
    attrs: { type: DataTypes.JSONB, allowNull: false, defaultValue: {} },
    status: { type: DataTypes.ENUM('draft', 'live'), allowNull: false, defaultValue: 'draft' },
    label: {
      type: DataTypes.VIRTUAL,
      get(this: Product) {
        return `${this.sku} ${this.name}`;
      },
    },
  },
  { sequelize, tableName: 'products', underscored: true },
);

The example shows:

  • a custom setter (set) that normalizes the value before it is stored, using setDataValue;
  • a VIRTUAL attribute with a getter: it is never stored, but is part of get() and toJSON();
  • ARRAY, JSONB and ENUM columns with defaults;
  • underscored: true, which maps createdAt to created_at and so on, and tableName to skip pluralization.

Other type helpers from v6 are available: ForeignKey<T> for foreign key attributes created by associations, and NonAttribute<T> for class fields that are not columns (for example, included associations).

Decorators ​

Models can also be declared with decorators (@Table, @Column, @HasMany, …) and registered with sequelize.addModels; see Decorators.

sequelize.define ​

define returns a model class without static attribute types. It is convenient in scripts and tests:

ts
const Order = sequelize.define(
  'Order',
  {
    number: { type: DataTypes.TEXT, allowNull: false },
    placedAt: { type: DataTypes.DATE, allowNull: false, defaultValue: DataTypes.NOW },
  },
  { paranoid: true },
);

paranoid: true adds deletedAt: destroy() sets it instead of deleting the row, finders skip such rows, and paranoid: false in find options includes them. restore() brings them back; destroy({ force: true }) deletes for real.

Using instances ​

ts
const product = await Product.create({ sku: 'ab-1', name: 'Anvil', tags: ['heavy'] });
product.attrs = { color: 'black' };
await product.save();

const line = await Line.create({ price: '2.50', qty: 4, period: '1 year 2 mons' });
// line.get('id') === '1' (BIGINT is returned as a string), line.get('total') === '10.00'

Instances track changes as in v6: changed(), previous(), save() writes only changed attributes, reload() reads the row again, and toJSON() returns plain values. Like v6, an attribute that was assigned a different value stays in changed() even when you set it back to the stored value.

create and bulkCreate accept fields to restrict which attributes are written. As in v6, the timestamps (createdAt, updatedAt), the version attribute and primary keys with a default are added to the list for you:

ts
const partial = await Product.create(
  { sku: 'cd-2', name: 'Anchor', status: 'live' },
  { fields: ['sku', 'name'] },
); // `status` is not written: the column default applies; timestamps are added for you

Model.schema(name) returns a copy of the model whose queries target another PostgreSQL schema, e.g. one per tenant. getTableName() of the copy returns { tableName, schema, delimiter }; the copy keeps the scope selection of the model it was made from, and unscoped() / scope() work on it. Hooks, scopes and associations are copied when schema() is called; later changes to the original are not seen by the copy.

ts
await sequelize.createSchema('tenant_a');
const TenantOrder = Order.schema('tenant_a');
await TenantOrder.sync();
await TenantOrder.create({ number: 'T-1' });
const tenantCount = await TenantOrder.count(); // counts "tenant_a"."Orders" only

Data types ​

DataTypes contains the Sequelize v6 types that PostgreSQL supports:

CategoryTypes
TextSTRING(n) (VARCHAR), CHAR(n), TEXT, CITEXT
NumbersINTEGER, SMALLINT, BIGINT, FLOAT, REAL, DOUBLE, DECIMAL(p, s)
Date and timeDATE (TIMESTAMP WITH TIME ZONE), TIMESTAMP, DATEONLY, TIME, INTERVAL
Other scalarsBOOLEAN, UUID, BLOB (BYTEA), INET, CIDR, MACADDR, MACADDR8, MONEY, XML, BIT(n), VARBIT(n), LTREE, TSVECTOR, TSQUERY
StructuredJSON, JSONB, HSTORE, ARRAY(type), RANGE(type), ENUM(...values)
PostGISGEOMETRY, GEOGRAPHY
Not storedVIRTUAL
Default valuesDataTypes.NOW (current time), DataTypes.UUIDV4 (random UUID generated in Node.js)

As in v6, BIGINT and DECIMAL values are returned as strings to avoid precision loss. INTERVAL values are strings in PostgreSQL output format ('1 year 2 mons'). RANGE values are arrays of two bounds, { value, inclusive } objects as in v6.

ENUM creates a PostgreSQL enum type named enum_<table>_<column>. sync({ alter: true }) adds new values to an existing enum type.

PostgreSQL-specific types ​

Types marked postgrelize extension do not exist in Sequelize v6.

ts
const Asset = sequelize.define(
  'Asset',
  {
    attrs: DataTypes.HSTORE,
    path: DataTypes.LTREE,
    price: DataTypes.MONEY,
    mac: DataTypes.MACADDR8,
    manifest: DataTypes.XML,
    flags: DataTypes.BIT(4),
    mask: DataTypes.VARBIT(16),
    filter: DataTypes.TSQUERY,
    seenAt: DataTypes.TIMESTAMP,
  },
  { timestamps: false },
);
await sequelize.sync();
ts
await Asset.create({
  attrs: { color: 'red', note: null },
  path: 'Top.Science.Astronomy',
  price: 12.5,
  mac: '08:00:2b:01:02:03:04:05',
  manifest: '<asset><id>1</id></asset>',
  flags: '1010',
  mask: '101',
  filter: "'fat' & 'rat'",
  seenAt: new Date(2024, 0, 2, 3, 4, 5),
});

const found = await Asset.findOne({ where: { attrs: { [Op.contains]: { color: 'red' } } } });
const descendants = await Asset.count({ where: literal("path <@ 'Top.Science'") });
  • postgrelize extension HSTORE operators and LTREE are postgrelize additions; HSTORE values are objects with string (or null) values, like Sequelize v6 with pg-hstore; Op.contains and Op.eq accept objects. Run CREATE EXTENSION hstore first. LTREE needs CREATE EXTENSION ltree; use literal() for its operators (<@, @>, ~).
  • postgrelize extension TIMESTAMP is TIMESTAMP WITHOUT TIME ZONE. Values are Dates whose local wall-clock time is the stored time, so they depend on the process time zone.
  • postgrelize extension MONEY is read as the server formats it (lc_monetary, for example '$12.50'). Write a number or a string.
  • postgrelize extension BIT(n) and VARBIT(n) values are strings of 0 and 1; BIT without a length is BIT(1).
  • postgrelize extension XML, MACADDR8 and TSQUERY values are strings.

Geometric types postgrelize extension ​

ts
const Place = sequelize.define(
  'Place',
  {
    name: DataTypes.STRING,
    at: DataTypes.POINT,
    area: DataTypes.BOX,
    route: DataTypes.PATH,
    zone: DataTypes.POLYGON,
    range: DataTypes.CIRCLE,
  },
  { timestamps: false },
);
await sequelize.sync();
ts
await Place.create({
  name: 'depot',
  at: { x: 1, y: 1 },
  area: [
    { x: 2, y: 2 },
    { x: 0, y: 0 },
  ],
  route: {
    closed: false,
    points: [
      { x: 0, y: 0 },
      { x: 1, y: 1 },
    ],
  },
  zone: [
    { x: 0, y: 0 },
    { x: 4, y: 0 },
    { x: 0, y: 4 },
  ],
  range: { x: 1, y: 1, radius: 5 },
});

const inside = await Place.count({ where: { area: { [Op.contains]: cast('(1,1)', 'point') } } });
const near = await Place.count({ where: literal('"at" <-> point(0,0) < 2') });
TypeValue
POINT{ x, y }
LINE{ a, b, c } (a·x + b·y + c = 0)
LSEG, BOX[Point, Point] (a box is returned with its upper-right corner first)
PATH{ points, closed }
POLYGONPoint[]
CIRCLE{ x, y, radius }

Text literals ('(1,2)') are accepted on write. Op.contains, Op.contained, Op.overlap, Op.strictLeft and Op.strictRight take the column's own shape; an operand of another type (a point against a box column) is a text literal wrapped in cast('(1,1)', 'point'). Distance (<->), intersection (?#) and the geometric functions go through literal() or fn(). point has no = operator in PostgreSQL (use ~=).

Multirange types postgrelize extension ​

ts
const Shift = sequelize.define(
  'Shift',
  {
    worker: DataTypes.STRING,
    hours: DataTypes.MULTIRANGE(DataTypes.INTEGER),
  },
  { timestamps: false },
);
await sequelize.sync();
ts
await Shift.create({
  worker: 'ann',
  hours: [
    [8, 12],
    [13, 17],
  ],
});
await Shift.create({ worker: 'bob', hours: [[18, 22]] });

const working = await Shift.findAll({
  where: { hours: { [Op.contains]: cast('9', 'int4') } },
});
const evening = await Shift.count({ where: { hours: { [Op.overlap]: [[20, 24]] } } });

DataTypes.MULTIRANGE(subtype) needs PostgreSQL 14+. The subtype is INTEGER (int4multirange), BIGINT, DECIMAL, TIMESTAMP (tsmultirange), DATE (tstzmultirange) or DATEONLY. A value is an array of ranges; each range is a [lower, upper] pair as for RANGE (plain values or { value, inclusive } bounds); [] is the empty multirange. Op.contains, Op.contained, Op.overlap, Op.strictLeft, Op.strictRight, Op.adjacent and the other range operators apply; an element operand (multirange @> int) is wrapped in cast('9', 'int4'). range_agg, unnest and the other multirange functions go through fn().

Composite types postgrelize extension ​

ts
const address = DataTypes.COMPOSITE('address', {
  street: DataTypes.TEXT,
  zip: DataTypes.INTEGER,
  verified: DataTypes.BOOLEAN,
});
await sequelize.query(address.createSql());

const Customer = sequelize.define(
  'Customer',
  { name: DataTypes.STRING, home: address },
  { timestamps: false },
);
await sequelize.sync();
ts
await Customer.create({
  name: 'ann',
  home: { street: 'Main St, 1', zip: 12345, verified: true },
});

const found = await Customer.findOne({
  where: { home: { [Op.eq]: { street: 'Main St, 1', zip: 12345, verified: true } } },
});

DataTypes.COMPOSITE(name, fields) maps a CREATE TYPE … AS (…) type to an object keyed by field name; each field is converted by its own data type (NULL is null; numbers, booleans, Date, Buffer, JSON and nested composites are supported, array fields are not). The type must exist: createSql() returns its CREATE TYPE statement (name and field names quoted), which you run once with sequelize.query(); sync() does not create it. where values compare the whole row (Op.eq); single fields go through literal('("home").zip = 12345').

Identity, generated and interval columns postgrelize extension ​

Column kinds that Sequelize v6 cannot create:

ts
const Line = sequelize.define(
  'Line',
  {
    id: { type: DataTypes.BIGINT, primaryKey: true, identity: 'always' },
    price: { type: DataTypes.DECIMAL(10, 2), allowNull: false },
    qty: { type: DataTypes.INTEGER, allowNull: false },
    total: { type: DataTypes.DECIMAL(12, 2), generated: { as: literal('"price" * "qty"') } },
    period: DataTypes.INTERVAL,
  },
  { timestamps: false },
);
  • identity: 'always' or 'byDefault' creates GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY instead of SERIAL. To write an explicit value into a GENERATED ALWAYS column (for example when importing rows with their ids), pass overriding: 'system' to create, bulkCreate, upsert or insert; overriding: 'user' makes a BY DEFAULT column ignore the supplied value.
ts
const imported = await Line.create(
  { id: '500', price: '1.00', qty: 1 },
  { overriding: 'system' },
); // GENERATED ALWAYS rejects an explicit id unless `overriding` says so
  • generated: { as: expression } creates a stored generated column. postgrelize never writes it in INSERT or UPDATE and reads the computed value back after each write. generated: { as, stored: false } creates a virtual generated column, which needs PostgreSQL 18.
  • INTERVAL is a plain data type here; Sequelize v6 has no interval type.

Model options ​

The options of init / define are the v6 ones: tableName, freezeTableName, schema, timestamps, createdAt / updatedAt / deletedAt (rename or disable with false), underscored, paranoid, version (optimistic locking), indexes, hooks, scopes, defaultScope, validate. postgrelize adds:

Defaults for all models go into the define option of the Sequelize constructor, e.g. new Sequelize(url, { define: { underscored: true } }).

API reference ​

Released under the MIT License.