Sling Academy
Home/Node.js/Sequelize.js: How to Delete a Record by ID

Sequelize.js: How to Delete a Record by ID

Last updated: December 29, 2023

Overview

Sequelize is a popular Node.js ORM (Object-Relational Mapping) library that makes it easy to work with relational databases such as MySQL, SQLite, PostgreSQL, and MSSQL. It provides a high-level abstraction for performing various database operations, including deleting records. This guide will take you through the steps of deleting a record by ID using Sequelize, a common task when managing data in applications.

The process involves defining the model representing the database table, then using the destruction method provided by Sequelize to remove a specific record based on its unique identifier. We’ll start with the basics and move on to more advanced use cases to ensure you have a comprehensive understanding of record deletion in Sequelize.js.

Prerequisites

  • Basic knowledge of JavaScript and Node.js
  • Node.js and npm (Node Package Manager) installed
  • A Sequelize project setup with a configured database connection
  • A model defined in Sequelize representing the table from which you want to delete records

Setting Up the Model

Before we can delete a record, we need a Sequelize model representing the database table. Here is a simple example of defining a model for a ‘User’ table:

const { Sequelize, DataTypes } = require('sequelize');
const sequelize = new Sequelize('sqlite::memory:'); // Example for SQLite

const User = sequelize.define('User', {
  // Model attributes are defined here
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  name: {
    type: DataTypes.STRING,
    allowNull: false
  }
});

Deleting a Record by ID

Once you have a model, use the destroy method to delete a record:

User.destroy({
  where: {
    id: 1
  }
}).then(() => {
  console.log('User deleted successfully.');
}).catch(error => {
  console.error('Error deleting user:', error);
});

This code will delete the user with an ID of 1. The operation is promise-based, allowing for either callbacks or async/await syntax.

Handling Constraints and Errors

It’s important to handle cases where the record might not exist or could have dependent records which need consideration. Sequelize will throw an error if such constraints are violated, and it’s crucial to catch and manage these errors effectively.

Advanced Deletion Patterns

Advanced scenarios might include bulk deletions or more complex conditions. For instance:

// Delete all users with a name starting with 'John'
User.destroy({
  where: {
    name: Sequelize.where(Sequelize.fn('name', Sequelize.col('name')), 'LIKE', 'John%')
  }
});

Sequelize’s destroy method is versatile and can accommodate various complex conditions for record deletion.

Transaction Support

Transactions are crucial in maintaining data integrity, especially when dealing with related records that all need to be deleted together. Sequelize supports transactions out of the box, and it’s recommended to use them for batch deletions or anytime multiple operations are carried out as a single unit of work.

const transaction = await sequelize.transaction();
try {
  await User.destroy({ where: { id: 10 }}, { transaction });
  // Other related operations...
  await transaction.commit();
} catch (error) {
  await transaction.rollback();
  console.error('Transaction rolled back due to error: ', error);
}

Summary

Deleting records by ID using Sequelize is a simple process once you understand the basic principles. We’ve covered the necessary steps, including setting up a model, using the destroy method, handling errors and constraints, using complex conditions, and managing transactions for data integrity. With these tools in your arsenal, you’ll be able to manage data effectively in your Node.js applications using Sequelize.

As with any database operation, always ensure to have proper backups and safeguards in place when deleting data, as these operations cannot be undone. Sequelize provides a robust framework for database interactions, and understanding how to leverage it for records deletion is invaluable for any developer working with Node.js and relational databases.

Next Article: What is Eager Loading in Sequelize.js?

Previous Article: Sequelize.js: How to Connect to Multiple Databases

Series: Sequelize.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates