Sequelize ORM

6.37.8 · active · verified Sat Apr 18

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to an SQLite database, define a User model, synchronize the schema, create a new user, and fetch all users. It uses `sequelize.sync({ force: true })` for simplicity, which will drop and re-create tables on each run.

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();

view raw JSON →