Sequelize Timestamps
Introduction
In Sequelize, timestamps refer to special fields that Sequelize can automatically manage in your database tables. These fields are typically used to track when a record was created and last updated.
The two main timestamp fields in Sequelize are,i) createdAt
This field stores the date and time when the record was initially created.ii) updatedAt
This field stores the date and time when the record was last updated.
When you define a model in Sequelize, you can enable or disable these timestamp fields. By default, Sequelize will add these fields to your models and automatically populate them:i) createdAt is set when a new record is inserted.
ii) updatedAt is set both when a record is created and whenever a record is updated.
Enabling/Disabling Timestamps
Timestamps are enabled by default in Sequelize. You can control this behavior using thetimestampsoption in your model definition.const { Sequelize, DataTypes } = require('sequelize'); const sequelize = new Sequelize('database', 'username', 'password', { dialect: 'mysql', // or any other supported dialect }); const User = sequelize.define('User', { username: { type: DataTypes.STRING, allowNull: false }, // other fields... }, { timestamps: true, // enables `createdAt` and `updatedAt` });If you want to disable timestamps, you can set the
timestampsoption tofalse,const User = sequelize.define('User', { username: { type: DataTypes.STRING, allowNull: false }, // other fields... }, { timestamps: false, // disables `createdAt` and `updatedAt` });Customizing Timestamp Field Names
You can also customize the names of these fields ifcreatedAtandupdatedAtdon't fit your naming conventions,const User = sequelize.define('User', { username: { type: DataTypes.STRING, allowNull: false }, // other fields... }, { timestamps: true, createdAt: 'created_at', // custom name for `createdAt` updatedAt: 'updated_at', // custom name for `updatedAt` });Soft Deletes with Timestamps
Sequelize also supports a
deletedAttimestamp for soft deletes, where a record isn't physically deleted from the database but is instead marked as deleted. This is enabled using theparanoidoption,const User = sequelize.define('User', { username: { type: DataTypes.STRING, allowNull: false }, // other fields... }, { timestamps: true, paranoid: true, // enables `deletedAt` for soft deletes });With
paranoidenabled, Sequelize will automatically set thedeletedAttimestamp when a record is "deleted" and exclude it from future queries unless specifically requested.