A Simple Tutorial on Implementing Sequelize in Node.js

Chris TiquisChris Tiquis
3 min read

Sequelize is a promise-based ORM (Object-Relational Mapping) for Node.js that supports multiple SQL dialects like MySQL, PostgreSQL, SQLite, and MSSQL. It helps you interact with your database using JavaScript objects instead of raw SQL queries.

This tutorial walks you through how to set up Sequelize in a basic Node.js app using MySQL as the database. You’ll learn how to connect to the database, define models, run migrations, and perform basic CRUD operations.


🛠 Prerequisites

Before you start, make sure you have the following installed:

  • Node.js (v14 or later)

  • MySQL (or another supported SQL database)

  • A code editor (VS Code recommended)

  • npm or yarn


Step 1: Initialize Your Node.js Project

mkdir sequelize-tutorial
cd sequelize-tutorial
npm init -y

Step 2: Install Required Packages

npm install sequelize mysql2
npm install --save-dev sequelize-cli
  • sequelize: The ORM library

  • mysql2: MySQL driver for Node.js (use pg for PostgreSQL)

  • sequelize-cli: Command line interface to manage Sequelize features like models and migrations


Step 3: Set Up Sequelize CLI

npx sequelize-cli init

This creates the following directory structure:

config/
models/
migrations/
seeders/

Step 4: Configure Database Connection

Open config/config.json and update the development section with your MySQL credentials:

{
  "development": {
    "username": "root",
    "password": "yourpassword",
    "database": "sequelize_db",
    "host": "127.0.0.1",
    "dialect": "mysql"
  }
}

Create the database:

mysql -u root -p
CREATE DATABASE sequelize_db;

Step 5: Create a Model and Migration

Let’s create a simple User model:

npx sequelize-cli model:generate --name User --attributes firstName:string,lastName:string,email:string

This generates:

  • A model in models/user.js

  • A migration in migrations/

Run the migration to create the table:

npx sequelize-cli db:migrate

Step 6: Use the Model in Code

Create a file called index.js:

const { Sequelize, DataTypes } = require('sequelize');
const sequelize = new Sequelize('sequelize_db', 'root', 'yourpassword', {
  host: '127.0.0.1',
  dialect: 'mysql',
});

const User = require('./models').User;

async function main() {
  try {
    await sequelize.authenticate();
    console.log('Database connected');

    // Create a user
    const newUser = await User.create({
      firstName: 'Jane',
      lastName: 'Doe',
      email: 'jane.doe@example.com',
    });

    console.log('User created:', newUser.toJSON());

    // Find all users
    const users = await User.findAll();
    console.log('All users:', users.map(user => user.toJSON()));
  } catch (error) {
    console.error('Error:', error);
  } finally {
    await sequelize.close();
  }
}

main();

Run the app:

node index.js

Step 7: Bonus – Add Validation or Associations

You can customize your model (models/user.js) with validations, default values, or associations with other models. Example:

email: {
  type: DataTypes.STRING,
  allowNull: false,
  unique: true,
  validate: {
    isEmail: true
  }
}

✅ Wrap Up

You now have a working Node.js app using Sequelize to connect to a MySQL database, run migrations, and perform CRUD operations. From here, you can scale up with associations, advanced queries, and data validations.

0
Subscribe to my newsletter

Read articles from Chris Tiquis directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Chris Tiquis
Chris Tiquis