Sequelize ORM
Sequelize is a robust, promise-based Node.js ORM (Object-Relational Mapper) for various SQL databases including Postgres, MySQL, MariaDB, SQLite, and Microsoft SQL Server. The current stable version is 6.37.8, with version 7 actively under development in alpha. It offers features like transaction support, relations, eager/lazy loading, and read replication. The project is actively seeking new maintainers to finalize the next major release.
Common errors
-
SequelizeConnectionError: connect ECONNREFUSED 127.0.0.1:5432
cause The database server is not running, is inaccessible, or connection details are incorrect.fixEnsure your database server is running and accessible. Verify host, port, username, and password in your Sequelize configuration. Check firewall rules if applicable. -
Error: Please install 'pg' module manually
cause The database dialect driver required by Sequelize (e.g., 'pg', 'mysql2') has not been installed.fixInstall the correct driver for your database: `npm install pg` (PostgreSQL), `npm install mysql2` (MySQL/MariaDB), `npm install sqlite3` (SQLite). -
SequelizeUniqueConstraintError: Validation error
cause An attempt was made to insert or update a record with a value that violates a unique constraint on a database field.fixImplement checks (e.g., using `Model.findOrCreate`) before creating records, or catch the `SequelizeUniqueConstraintError` and handle the duplicate entry gracefully. -
SequelizeDatabaseError: ER_BAD_FIELD_ERROR: Unknown column '...' in 'field list'
cause The database schema does not match the Sequelize model definition, often due to missing or outdated migrations.fixRun database migrations to ensure your schema is up-to-date with your Sequelize models. Double-check column names and aliases in your queries.
Warnings
- breaking Upgrading from Sequelize v5 to v6 introduces several breaking changes that require code modifications.
- breaking A security vulnerability (CVE-2026-30951) allowed validation bypass in JSON where clauses, potentially leading to SQL injection.
- gotcha Sequelize requires a separate database dialect driver package to be installed manually (e.g., 'pg' for PostgreSQL, 'mysql2' for MySQL, 'sqlite3' for SQLite).
- gotcha The Sequelize project is actively seeking new maintainers, which might impact the pace of feature development or critical bug fixes for future major versions if not enough contributors join.
Install
-
npm install sequelize -
yarn add sequelize -
pnpm add sequelize
Imports
- Sequelize
const { Sequelize } = require('sequelize');import { Sequelize } from 'sequelize'; - DataTypes
const { DataTypes } = require('sequelize');import { DataTypes } from 'sequelize'; - Model
const { Model } = require('sequelize');import { Model } from 'sequelize';
Quickstart
import { Sequelize, DataTypes, Model } from 'sequelize';
const sequelize = new Sequelize({
dialect: 'sqlite',
storage: 'database.sqlite',
logging: false // Disable logging for cleaner output
});
class User extends Model {}
User.init({
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
username: {
type: DataTypes.STRING,
allowNull: false,
unique: true
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true
}
}, {
sequelize,
modelName: 'User'
});
async function run() {
try {
await sequelize.authenticate();
console.log('Connection has been established successfully.');
await sequelize.sync({ force: true }); // This will drop existing tables
console.log('All models were synchronized successfully.');
const jane = await User.create({ username: 'JaneDoe', email: 'jane.doe@example.com' });
console.log(`Created user: ${jane.username}`);
const users = await User.findAll();
console.log('All users:', users.map(u => u.toJSON()));
} catch (error) {
console.error('Unable to connect to the database:', error);
} finally {
await sequelize.close();
}
}
run();