createdAt and updatedAt fields in Sequelize.js

Updated: December 29, 2023 By: Guest Contributor Post a comment

Overview

Sequelize, an ORM (Object-Relational Mapper) for Node.js, facilitates the management of database operations using JavaScript. In this tutorial, we delve into the automatic timestamp attributes createdAt and updatedAt, exploring how Sequelize uses these fields to track the creation time and the last update time of our model instances.

Defining Models with Timestamps

In Sequelize, when defining a new model, the timestamps are included by default.

const User = sequelize.define('User', {
  // Model attributes
}, {
  // Model options
  timestamps: true // Default is true
});

This creates createdAt and updatedAt fields which track when a record is inserted and last updated.

Customizing Timestamp Names

If you prefer different column names for these timestamps, Sequelize allows such customization:

const User = sequelize.define('User', {
  // Model attributes
}, {
  timestamps: true,
  createdAt: 'created_at',
  updatedAt: 'updated_at'
});

Disabling Timestamps

If you decide not to use timestamps, you can disable them as follows:

const User = sequelize.define('User', {
  // Model attributes
}, {
  timestamps: false
});

Using Timestamps in Queries

The createdAt and updatedAt fields can be particularly useful in queries. For instance, you can retrieve records created after a certain date:

User.findAll({
  where: {
    createdAt: {
      [Sequelize.Op.gt]: new Date(new Date() - 24 * 60 * 60 * 1000)
    }
  }
});

Or, updating a model instance, Sequelize will automatically modify the updatedAt field:

User.update({ name: 'Jane Doe' }, {
  where: { id: 1 }
});

Handling Timestamps with Hooks

Beyond the automatic behavior, you can use hooks to interact with these timestamps:

User.beforeUpdate((user, options) => {
  user.updatedAt = new Date();
});

Managing Time Zones

Sequelize timestamps are by default in UTC. To use a different time zone, you can configure the Sequelize instance:

const sequelize = new Sequelize('database', 'username', 'password', {
  dialect: 'mysql',
  timezone: '+02:00' // for example, Central European Time
});

Advanced Timestamp Customizations

You can further customize behavior by specifying field attributes on the timestamp fields:

const User = sequelize.define('User', {
  // Model attributes
  created_at: {
    type: Sequelize.DATE,
    allowNull: false,
    defaultValue: Sequelize.NOW
  },
  //... other fields ...
}, {
  timestamps: true,
  createdAt: 'created_at',
  updatedAt: 'updated_at'
});

Conclusion

To summarize, Sequelize provides convenient timestamp fields createdAt and updatedAt which help in tracking when records are created and updated without manual intervention. Customization options give developers fine-grained control over how these fields behave and interact with the rest of the application.