Sling Academy
Home/Node.js/Filtering by Multiple Conditions in Sequelize

Filtering by Multiple Conditions in Sequelize

Last updated: December 29, 2023

Overview

Sequelize is a popular Node.js ORM for managing relational databases. It provides a rich set of tools for building dynamic queries using JavaScript. This tutorial will guide you through different ways to filter queries using multiple conditions in Sequelize, ensuring your application can handle complex data retrieval with ease.

Basic Filtering with where Clauses

Filtering in Sequelize starts with the where option. Here’s a simple example:

const users = await User.findAll({
  where: {
    isActive: true
  }
});

This code fetches all active users from the database.

Combining Conditions

To combine conditions, you can use Op.and:

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

const users = await User.findAll({
  where: {
    [Op.and]: [{ isActive: true }, { age: { [Op.gt]: 30 } }]
  }
});

This fetches active users who are older than 30.

Using Operators for Complex Filters

Sequelize provides various operators for complex filtering conditions:

  • Op.or: for logical OR.
  • Op.gt, Op.gte: for ‘greater than’ and ‘greater than or equal’ comparisons.
  • Op.lt, Op.lte: for ‘less than’ and ‘less than or equal’ comparisons.
  • Op.ne, Op.eq: for ‘not equal’ and ‘equal’ comparisons.

Here’s an example using a combination of these operators:

const users = await User.findAll({
  where: {
    [Op.or]: [
      { age: { [Op.lt]: 20 } },
      { age: { [Op.gt]: 50 } }
    ]
  }
});

The above code finds users who are either younger than 20 or older than 50.

Advanced Filtering with Nested Conditions

For more complex queries, you can nest conditions:

const users = await User.findAll({
  where: {
    [Op.and]: [
      { [Op.or]: [{ age: { [Op.lt]: 20 } }, { age: { [Op.gt]: 60 } }] },
      { isActive: true }
    ]
  }
});

This retrieves active users who are either below 20 or above 60 years old.

Filtering with Associations

When dealing with associated models, filters can be applied as follows:

const users = await User.findAll({
  include: [
    {
      model: Post,
      as: 'posts',
      where: { published: true }
    }
  ],
  where: {
    isActive: true
  }
});

This finds active users with published posts.

Dynamic Filtering for API Queries

For APIs, filters might come from parameters. Here’s how to build a dynamic query:

const buildQuery = (filters) => {
  const query = { where: {} };
  if(filters.isActive) {
    query.where.isActive = filters.isActive === 'true';
  }
  if(filters.age) {
    query.where.age = { [Op.gt]: Number(filters.age) };
  }
  return query;
};

const users = await User.findAll(buildQuery(apiFilters));

This allows for a flexible and scalable API endpoint.

Performance Considerations

When performing complex queries:

  • Use indexes on columns that are often searched.
  • Minimize the use of Op.or with indices, as it can affect performance.

Always test your queries for performance implications.

Conclusion

This tutorial covered the essentials of filtering by multiple conditions in Sequelize. As you start implementing more complex queries, always consider performance and the maintainability of your code. Happy querying!

Next Article: Selecting a Single Random Record in Sequelize.js (3 Ways)

Previous Article: Mastering the LIKE Condition 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