Sling Academy
Home/Node.js/createdAt and updatedAt fields in Sequelize.js

createdAt and updatedAt fields in Sequelize.js

Last updated: December 29, 2023

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.

Next Article: Dates, Timestamps, and Timespans in Sequelize.js

Previous Article: Sequelize: How to Update a Record by ID

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