Support Online
Skip to main content

Using Sequelize with Node.js and MySQL

This guide teaches you step by step MySQL database administration using Sequelize ORM in Node.js projects.
The goal is to create a secure, readable and maintainable data layer without writing raw SQL.

Technical Summary

Sequelize is an ORM library that makes it easier to work with relational databases such as MySQL in Node.js-based applications.
In this guide; Starting from installation, model creation, CRUD operations, table relationships, secure configuration and migration processes are discussed.


What Will You Learn in This Guide?

  • What is Sequelize and why is it used?
  • Securely establishing a MySQL connection
  • Creating a model (table)
  • Adding, listing and deleting data (CRUD)
  • One-to-Many table relationships
  • Safe use of Raw SQL queries
  • Migration and best practices for the production environment

Prerequisites

  • Node.js (LTS version recommended)
  • Working MySQL service
  • JavaScript and basic SQL knowledge

1. Project Setup and Sequelize Installation

mkdir sequelize-projesi
cd sequelize-projesi
npm init -y
npm install sequelize mysql2 dotenv
  • These steps create the Node.js project structure and install the necessary packages.

2. Secure Database Connection with Environment Variables

  1. .env File

DB_ISMI=kutuphane_db
DB_KULLANICI=genix_user
DB_SIFRE=GucluSifre123!
DB_HOST=localhost
DB_DIALECT=mysql
  • This structure prevents sensitive information from being embedded in the source code.

Sequelize Connection Configuration


require('dotenv').config();
const { Sequelize } = require("sequelize");

const sequelize = new Sequelize(
process.env.DB_ISMI,
process.env.DB_KULLANICI,
process.env.DB_SIFRE,
{
host: process.env.DB_HOST,
dialect: process.env.DB_DIALECT
}
);

sequelize.authenticate()
.then(() => console.log("Veritabanı bağlantısı başarılı"))
.catch(err => console.error("Bağlantı hatası:", err));
  • This code tests the database connection during application startup.

3. Creating a Model (Table)


const { DataTypes } = require("sequelize");

const Kitap = sequelize.define("kitaplar", {
baslik: { type: DataTypes.STRING, allowNull: false },
yazar: { type: DataTypes.STRING, allowNull: false },
yayin_tarihi: DataTypes.DATEONLY
});

sequelize.sync();
  • Sequelize automatically creates a table based on the model definition.

4. CRUD Operations

  1. Adding Data

Kitap.create({
baslik: "Temiz Kod",
yazar: "Robert C. Martin",
yayin_tarihi: "2008-08-01"
});

  1. Data Listing

Kitap.findAll();

  1. Conditional Query

Kitap.findOne({ where: { id: 1 } });

  1. Delete Data

Kitap.destroy({ where: { id: 1 } });
  • These operations provide basic database management without writing SQL.

5. Table Associations

  1. One-to-Many Relationship Example

const Ogrenci = sequelize.define("ogrenciler", {
isim: DataTypes.STRING
});

const Ders = sequelize.define("dersler", {
ders_adi: DataTypes.STRING
});

Ders.hasMany(Ogrenci);
Ogrenci.belongsTo(Ders);
  • This structure automatically adds a foreign key to the students table.

6. Using Raw SQL Queries


sequelize.query(
'SELECT * FROM kitaplar WHERE id = :id',
{
replacements: { id: 1 },
type: sequelize.QueryTypes.SELECT
}
);
  • Using replacements reduces the risk of SQL Injection.

7. Migration and Best Practices

  1. The use of sequelize.sync() is not recommended in production environments. Instead, migration mechanism should be preferred.

Sequelize CLI Installation


npm install --save-dev sequelize-cli
npx sequelize-cli init

Migration usage:

  1. Versions schema changes

  2. Provides rollback opportunity

  3. Provides consistency in teamwork


Frequently Asked Questions

1. What databases does Sequelize support? MySQL, PostgreSQL, SQLite, MariaDB and Microsoft SQL Server.

2. What does sync force true do? Deletes and recreates tables. It should not be used in a production environment.

3. Does ORM cause performance loss? For most applications the difference is negligible.

4. What to check for connection errors? .env file, MySQL service status and port access.

5. Is there TypeScript support? Yes. Supported by sequelize-typescript package.


Result

Using Sequelize with this guide:

  • Safe,

  • Readable,

  • Scalable

You can develop Node.js and MySQL based applications.

GenixNode VDS solutions can be evaluated to test this infrastructure in a high-performance environment.