Sequelize Paranoid
Introduction
In Sequelize, the
paranoidoption 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 adeletedAttimestamp 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
deletedAtcolumn is automatically added by Sequelize.iii) You can restore soft-deleted records or include them in queries as needed.
How it works
i) Without paranoid: A record is physically deleted from the database when you calldestroy().ii) With paranoid: A record is not actually removed from the database when you call
destroy(). Instead, thedeletedAtcolumn is populated with the current timestamp, marking it as deleted, but keeping the record in the table.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 theuserstable, Sequelize will set thedeletedAtfield for the user withid = 1.Benefits of using paranoid
i) Soft Deletes: You can "undo" the deletion by simply setting the
deletedAtfield back tonull.ii) Hidden by Default: Queries like
findOneandfindAllwill ignore records wheredeletedAtis notnull. This way, soft-deleted records won't show up unless explicitly requested.Retrieving Soft-Deleted Records
If you want to query soft-deleted records, you can do this by passing the
paranoid: falseoption.User.findAll({ where: { email: 'test@example.com' }, paranoid: false // include soft-deleted records in the results });