You're reading for free via habtesoft's Friend Link. Become a member to access the best of Medium.
Member-only story
Getting Started with Sequelize in Node.js: A Step-by-Step Tutorial

Sequelize is a powerful ORM (Object-Relational Mapping) for Node.js that makes it easy to work with SQL databases like MySQL, PostgreSQL, SQLite, and Microsoft SQL Server. In this tutorial, we’ll walk through the steps to get started with Sequelize, from installation to defining models and running basic queries.
Not a Medium member? Read this article here
Step 1: Setting Up Your Project
First, let’s set up a new Node.js project.
- Initialize a Node.js Project:
Open your terminal and run the following commands to create a new directory and initialize a Node.js project:
mkdir sequelize-tutorial
cd sequelize-tutorial
npm init -y
2. Install Sequelize and a Database Driver:
Next, you’ll need to install Sequelize and the appropriate database driver for your chosen database. In this example, we’ll use MySQL, but you can choose any supported database.
npm install sequelize mysql2
If you’re using PostgreSQL, SQLite, or another database, replace mysql2
with the appropriate driver, such as pg
for PostgreSQL or sqlite3
for SQLite.
Step 2: Setting Up Sequelize
Now that we have Sequelize installed, let’s set it up to connect to our database.
- Create a Sequelize Instance:
Create a new file called sequelize.js
in the root of your project. This file will contain the configuration for your Sequelize instance.
const { Sequelize } = require('sequelize');
const sequelize = new Sequelize('database_name', 'username', 'password', {
host: 'localhost',
dialect: 'mysql', // Change to 'postgres', 'sqlite', etc., if using a different database
});
module.exports = sequelize;
Replace database_name
, username
, and password
with your actual database credentials.
2. Test the Database Connection:
It’s a good idea to test the connection to your database. You can do this by creating a simple script:
const sequelize = require('./sequelize');
sequelize.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch((err) => {
console.error('Unable to connect to the database:', err);
});
Run the script with:
node sequelize.js
If the connection is successful, you’ll see a confirmation message in the terminal.
Step 3: Defining Models
Models in Sequelize represent tables in your database. Let’s define a basic model for a User
table.
- Create a Model File:
Create a new directory called models
and inside it, create a file called user.js
.
const { DataTypes } = require('sequelize');
const sequelize = require('../sequelize');
const User = sequelize.define('User', {
username: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
type: DataTypes.STRING,
allowNull: false,
},
password: {
type: DataTypes.STRING,
allowNull: false,
},
});
module.exports = User;
Here, we define a User
model with three fields: username
, email
, and password
.
Step 4: Syncing Models with the Database
Sequelize provides a powerful sync()
method to create tables in your database based on your models.
- Sync the Database:
Create a new file called sync.js
to sync the models:
const sequelize = require('./sequelize');
const User = require('./models/user');
sequelize.sync({ force: true })
.then(() => {
console.log('Database & tables created!');
});
Run the sync script with:
node sync.js
This will create the User
table in your database. The force: true
option drops the table if it already exists, so use it carefully.
Step 5: Creating and Querying Records
Now that our table is set up, let’s add some data and perform basic queries.
- Create a New Record:
Create a new file called create-user.js
to add a new user to the database:
const User = require('./models/user');
User.create({
username: 'johndoe',
email: 'johndoe@example.com',
password: 'password123',
}).then(user => {
console.log('User created:', user.toJSON());
});
Run the script with:
node create-user.js
2. Query the Database:
Create a new file called find-users.js
to query the users in the database:
const User = require('./models/user');
User.findAll().then(users => {
console.log('All users:', JSON.stringify(users, null, 2));
});
Run the script with:
node find-users.js
This will retrieve and display all users in the User
table.
Step 6: Updating and Deleting Records
Sequelize also makes it easy to update and delete records.
- Update a Record:
Create a new file called update-user.js
to update a user's email:
const User = require('./models/user');
User.update({ email: 'newemail@example.com' }, {
where: {
username: 'johndoe'
}
}).then(() => {
console.log('User updated');
});
Run the script with:
node update-user.js
2. Delete a Record:
Create a new file called delete-user.js
to delete a user:
const User = require('./models/user');
User.destroy({
where: {
username: 'johndoe'
}
}).then(() => {
console.log('User deleted');
});
Run the script with:
node delete-user.js
You’ve now covered the basics of getting started with Sequelize in a Node.js project. From setting up a connection to defining models, syncing with the database, and performing CRUD operations, Sequelize makes interacting with SQL databases in Node.js straightforward and efficient.
To expand your knowledge further, explore Sequelize’s advanced features like associations, transactions, and migrations.