ORM with Express.js and Sequelize

🎯 Objectives: ORM with Express.js and Sequelize

ORM with Express.js and Sequelize

Object-Relational Mapping (ORM) in Express.js using Sequelize

1. What is ORM in Express.js?

ORM allows JavaScript developers to interact with SQL databases using object-oriented code instead of raw SQL queries. In Express.js, the most commonly used ORM is Sequelize.

2. Why Use Sequelize in Express.js?

  • Simplifies database interaction
  • Enables reusable models and cleaner code
  • Reduces SQL code
  • Prevents SQL injection
  • Supports multiple databases (MySQL, PostgreSQL, SQLite)

3. Installing Sequelize and Setting Up

npm install sequelize mysql2 express
  

Initialize Sequelize

npx sequelize-cli init
  

This creates the folders: models, migrations, config, and seeders

4. Configuration

Edit config/config.json or config/config.js and set your DB connection:

{
  "development": {
    "username": "root",
    "password": "your_password",
    "database": "orm_example",
    "host": "127.0.0.1",
    "dialect": "mysql"
  }
}
  

5. Create a Model

npx sequelize-cli model:generate --name Student --attributes name:string,email:string,course:string
  

This creates:

  • Model: models/student.js
  • Migration file: migrations/xxxxx-create-student.js

Run Migration

npx sequelize-cli db:migrate
  

6. Define Express Server

// server.js
const express = require('express');
const app = express();
const { Student } = require('./models');
app.use(express.json());
  

7. CRUD Routes Using ORM

Create Student

app.post('/students', async (req, res) => {
  const { name, email, course } = req.body;
  const student = await Student.create({ name, email, course });
  res.json(student);
});
  

Read All Students

app.get('/students', async (req, res) => {
  const students = await Student.findAll();
  res.json(students);
});
  

Read One Student

app.get('/students/:id', async (req, res) => {
  const student = await Student.findByPk(req.params.id);
  res.json(student);
});
  

Update Student

app.put('/students/:id', async (req, res) => {
  const { name, email, course } = req.body;
  const student = await Student.findByPk(req.params.id);
  await student.update({ name, email, course });
  res.json(student);
});
  

Delete Student

app.delete('/students/:id', async (req, res) => {
  const student = await Student.findByPk(req.params.id);
  await student.destroy();
  res.send('Deleted');
});
  

Start Server

app.listen(3000, () => {
  console.log("Server is running on http://localhost:3000");
});
  

8. Model File Example

// models/student.js

'use strict';
module.exports = (sequelize, DataTypes) => {
  const Student = sequelize.define('Student', {
    name: DataTypes.STRING,
    email: DataTypes.STRING,
    course: DataTypes.STRING
  }, {});
  return Student;
};
  

9. Summary of Sequelize ORM in Express.js

Concept Usage
Model Definition sequelize.define()
Create Model.create()
Read All Model.findAll()
Read One Model.findByPk(id)
Update instance.update()
Delete instance.destroy()

10. When to Use ORM in Express.js

  • When building CRUD-based applications
  • When working with SQL databases like MySQL or PostgreSQL
  • When you want fast development and secure queries

11. When to Avoid ORM

  • When you need complex, highly-optimized SQL queries
  • When raw SQL is necessary for performance
  • When using NoSQL databases (MongoDB uses ODM like Mongoose instead)

πŸ“– Reference Book: N/A

πŸ“„ Page: 1.2