Sling Academy
Home/Node.js/How to Filter by Date in Sequelize.js

How to Filter by Date in Sequelize.js

Last updated: December 29, 2023

Introduction

Sequelize is a robust ORM (Object-Relational Mapping) library for Node.js, which facilitates the management of relational databases. One common requirement when dealing with databases is to filter data by dates. This tutorial will guide you through different strategies for filtering records by date in Sequelize, including basic comparisons, range queries, and using Sequelize’s query operators for more advanced scenarios.

Prerequisites

  • Basic knowledge of Node.js and Sequelize.
  • A Sequelize setup with at least one model configured.

Simple Date Comparison

Let’s start with the simplest case – filtering data by an exact date match. Here’s how you might retrieve records that match a specific date.

const { Op } = require('sequelize');

// Assuming you have a model User with a `createdAt` field
User.findAll({
  where: {
    createdAt: {
      [Op.eq]: new Date('2021-03-17')
    }
  }
});

Date Range Filtering

Often, you will want to retrieve records within a certain date range. Sequelize makes this easy with its range operators.

User.findAll({
  where: {
    createdAt: {
      [Op.between]: [new Date('2021-03-01'), new Date('2021-03-31')]
    }
  }
});

// Or, using greater than and less than	
User.findAll({
  where: {
    createdAt: {
      [Op.gt]: new Date('2021-03-01'),
      [Op.lt]: new Date('2021-04-01')
    }
  }
});

Advanced Date Filtering

Sequelize also allows you to perform more complex date queries, such as looking for records with a date part (e.g., records created on any Monday).

const sequelize = require('sequelize');

User.findAll({
  where: sequelize.where(sequelize.fn('DAYOFWEEK', sequelize.col('createdAt')), 2)
});

Timezone Considerations

When dealing with dates, timezones can be a challenge. Here’s how you might convert UTC dates to a local timezone before performing a query.

// Assuming you use a library like `moment-timezone`
const moment = require('moment-timezone');

const startDate = moment.tz('2021-03-01', 'America/Los_Angeles').toDate();
const endDate = moment.tz('2021-03-31', 'America/Los_Angeles').endOf('day').toDate();

User.findAll({
  where: {
    createdAt: {
      [Op.between]: [startDate, endDate]
    }
  }
});

Handling Null Dates

In some cases, you may have to deal with null dates. Here’s how you can filter out records with a null date field.

User.findAll({
  where: {
    createdAt: {
      [Op.not]: null
    }
  }
});

Performance Tips

Filtering by date can be expensive in terms of database performance, especially with large datasets. To improve performance, consider the following:

  • Always ensure that you have indexes on the date columns used for filtering.
  • Try to avoid unnecessary complex calculations in your date filters.
  • Paginate results to minimize the amount of data transferred.

Conclusion

In this tutorial, we’ve covered various ways to filter data by date in Sequelize, ranging from basic equality checks to more complex queries and considerations for timezone conversions. With these tools at your disposal, you should be well-equipped to handle many common date-filtering requirements in your Node.js applications using Sequelize.

Next Article: How to Execute Raw SQL Queries in Sequelize

Previous Article: How to Implement Pagination 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