Skip to main content

Command Palette

Search for a command to run...

Sequelize Paranoid

Published
View as Markdown
  1. Introduction

    In Sequelize, the paranoid option is a feature used in models to enable soft deletes. When a model is set as paranoid, instead of permanently deleting records from the database, Sequelize will set a deletedAt timestamp field. This allows you to retain the record in the database while marking it as "deleted" without actually removing it.
    i) Paranoid = true - Activates soft deletes (marks the record as deleted without actually removing it).

    ii) The deletedAt column is automatically added by Sequelize.

    iii) You can restore soft-deleted records or include them in queries as needed.

  2. How it works
    i) Without paranoid: A record is physically deleted from the database when you call destroy().

    ii) With paranoid: A record is not actually removed from the database when you call destroy(). Instead, the deletedAt column is populated with the current timestamp, marking it as deleted, but keeping the record in the table.

  3. Example

     const User = sequelize.define('User', {
       username: Sequelize.STRING,
       email: Sequelize.STRING
     }, {
       paranoid: true
     });
    

    Here, if you call User.destroy({ where: { id: 1 } }), instead of removing the record from the users table, Sequelize will set the deletedAt field for the user with id = 1.

  4. Benefits of using paranoid

    i) Soft Deletes: You can "undo" the deletion by simply setting the deletedAt field back to null.

    ii) Hidden by Default: Queries like findOne and findAll will ignore records where deletedAt is not null. This way, soft-deleted records won't show up unless explicitly requested.

  5. Retrieving Soft-Deleted Records

    If you want to query soft-deleted records, you can do this by passing the paranoid: false option.

     User.findAll({
       where: { email: 'test@example.com' },
       paranoid: false // include soft-deleted records in the results
     });