0
0
Expressframework~5 mins

CRUD operations with Sequelize in Express

Choose your learning style9 modes available
Introduction

CRUD operations let you create, read, update, and delete data in a database easily. Sequelize helps you do this in Node.js apps without writing raw SQL.

When building a web app that needs to save user info like profiles or posts.
When you want to manage data in a database using JavaScript code.
When you need to update or remove records based on user actions.
When you want to fetch data from a database to show on a webpage.
When you want to keep your database code organized and easy to read.
Syntax
Express
const Model = require('./models/Model');

// Create
Model.create({ field1: value1, field2: value2 });

// Read
Model.findAll();
Model.findOne({ where: { field: value } });

// Update
Model.update({ fieldToUpdate: newValue }, { where: { id: someId } });

// Delete
Model.destroy({ where: { id: someId } });

Use create() to add new data.

Use findAll() or findOne() to get data.

Use update() to change existing data.

Use destroy() to remove data.

Examples
Adds a new user named Alice who is 25 years old.
Express
User.create({ name: 'Alice', age: 25 });
Gets all users from the database.
Express
User.findAll();
Updates Alice's age to 26.
Express
User.update({ age: 26 }, { where: { name: 'Alice' } });
Deletes the user named Alice.
Express
User.destroy({ where: { name: 'Alice' } });
Sample Program

This Express app uses Sequelize to manage users in a database. It supports creating, reading, updating, and deleting users through HTTP routes.

Try sending JSON data to POST /users to add a user, GET /users to list users, PUT /users/:id to update, and DELETE /users/:id to remove.

Express
import express from 'express';
import { Sequelize, DataTypes } from 'sequelize';

const app = express();
app.use(express.json());

const sequelize = new Sequelize('sqlite::memory:');

const User = sequelize.define('User', {
  name: {
    type: DataTypes.STRING,
    allowNull: false
  },
  age: {
    type: DataTypes.INTEGER
  }
});

app.post('/users', async (req, res) => {
  const user = await User.create(req.body);
  res.json(user);
});

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

app.put('/users/:id', async (req, res) => {
  const { id } = req.params;
  await User.update(req.body, { where: { id } });
  const updatedUser = await User.findOne({ where: { id } });
  res.json(updatedUser);
});

app.delete('/users/:id', async (req, res) => {
  const { id } = req.params;
  await User.destroy({ where: { id } });
  res.json({ message: 'User deleted' });
});

(async () => {
  await sequelize.sync({ force: true });
  app.listen(3000, () => console.log('Server running on http://localhost:3000'));
})();
OutputSuccess
Important Notes

Always handle errors in real apps to avoid crashes.

Sequelize uses promises, so use async/await for cleaner code.

Use sequelize.sync() to create tables automatically.

Summary

CRUD means Create, Read, Update, Delete data.

Sequelize lets you do CRUD with JavaScript instead of SQL.

Use Sequelize methods like create(), findAll(), update(), and destroy().