Sling Academy
Home/Node.js/A Deep Dive into Sequelize’s Timestamps

A Deep Dive into Sequelize’s Timestamps

Last updated: December 29, 2023

Overview

In ORM packages like Sequelize, timestamps play a crucial role in tracking when database records are created and updated. Sequelize provides built-in features that automatically manage these timestamps, ensuring an additional layer of data integrity in your applications. In this article, we will explore how Sequelize handles timestamps, how to customize them, and good practices for using timestamps in our Sequelize models.

Timestamps in Models

By default, when you define a Sequelize model, it comes with two timestamps: createdAt and updatedAt. These are managed automatically by Sequelize and correspond to the created_at and updated_at fields in your database table. Here is a basic example of defining a model with these timestamps:

const User = sequelize.define('User', {
  username: Sequelize.STRING,
}, {
  // options
});

This code snippet will result in Sequelize including created_at and updated_at columns in the ‘Users’ table.

Customizing Timestamp Names

Sequelize allows you to customize the names of timestamp fields. If your database schema uses different column names for storing timestamps, you can specify them like so:

const User = sequelize.define('User', {
  username: Sequelize.STRING,
}, {
  createdAt: 'creationDate',
  updatedAt: 'updateDate',
  // more options
});

With this approach, your model will now refer to the creationDate and updateDate fields in the database table for managing the record creation and update times.

Disabling Timestamps

There might be cases where you do not want Sequelize to manage timestamps. You can disable them altogether using the following configuration:

const User = sequelize.define('User', {
  username: Sequelize.STRING,
}, {
  timestamps: false,
  // other model options
});

After this, Sequelize will not create or update the createdAt and updatedAt fields, and they will need to be manually managed if necessary.

Advanced Uses of Timestamps

There are more sophisticated ways to work with timestamps in Sequelize. For instance, you might want to only include a createdAt timestamp and not an updatedAt one. This is also possible:

const User = sequelize.define('User', {
  username: Sequelize.STRING,
}, {
  createdAt: true,
  updatedAt: false,
  // other options
});

This configuration will only manage the createdAt field, while leaving out updatedAt.

Timezone Handling

Handling timezones is an important aspect of dealing with timestamps. Sequelize can store timestamps in UTC and convert them to the local time of the server, or it can work directly with the database’s time settings. Here’s how you can configure timezone handling:

const sequelize = new Sequelize('database', 'username', 'password', {
  // other options
  dialect: 'mysql',
  dialectOptions: {
    useUTC: false, //for reading from database
  },
  timezone: '+00:00', //for writing to database
});

The timezone configuration ensures that when Sequelize writes timestamps to the database, it uses the specified timezone offset.

Timestamp Precision

Sequelize also provides options for specifying the precision of your timestamps:

const DataTypes = Sequelize.DataTypes;
const User = sequelize.define('User', {
  username: DataTypes.STRING,
  createdAt: DataTypes.DATE(3),
  updatedAt: DataTypes.DATE(3)
});

This example sets the number of decimal places for the seconds portion of the timestamp columns, which, for some databases, means millisecond precision.

Handling Timestamp Functionality Manually

There are cases where you might want full control over the timestamp data. Here’s how you can manage timestamp fields manually:

const now = new Date();
User.create({
  username: 'johndoe',
  createdAt: now,
  updatedAt: now
});
User.update({
  username: 'johnsmith',
  updatedAt: new Date()
}, {
  where: { username: 'johndoe' }
});

While Sequelize can handle this automatically, manually setting timestamps can be useful when you have specific requirements for how and when timestamps should be updated.

Conclusion

In this tutorial, we have taken a comprehensive look at the timestamps feature in Sequelize. Choosing to allow Sequelize to handle these fields can save time in development and prevent potential mistakes. However, knowing how to customize and manually manage them can be just as important for meeting specific application needs. As always with Sequelize, flexibility is a key benefit, and timestamps are yet another example of how the ORM caters to a variety of uses cases.

Next Article: How to Set Default Values in Sequelize.js (3 Ways)

Previous Article: How to Set Unsigned Integer Field in Sequelize.js

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