Sequelize.js: “Greater Than or Equal To” Operator Usage

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

Overview

Using Sequelize.js, developers can comfortably interact with databases through an ORM lens. One common need is to query records that meet certain threshold criteria, such as finding all users who have logged in a certain number of times, or retrieving orders over a fixed amount. The Greater than or equal to operator (>=) comes in handy for such queries. In this tutorial, we will explore how to effectively utilize Sequelize’s ‘greater than or equal to’ functionality with a series of increasingly complex examples.

Basic Usage

To begin with, let’s consider a simple model named ‘User’ with an attribute ‘loginCount’. We want to find all users who have logged in at least 10 times. In Sequelize, your query would look as follows:

const { Op } = require('sequelize');
let minLogins = 10;
User.findAll({
  where: {
    loginCount: {
      [Op.gte]: minLogins
    }
  }
});

We used the ‘Op’ object provided by Sequelize to specify the comparison operator. The ‘Op.gte’ property corresponds to the ‘>=’, or ‘greater than or equal to’, operator.

Combining Conditions

Sometimes, you might want to combine the ‘>=’ operator with other conditions. For instance, consider finding active users with login count greater than or equal to ‘minLogins’ and who have ‘isActive’ set to true.

User.findAll({
  where: {
    loginCount: {
      [Op.gte]: minLogins
    },
    isActive: true
  }
});

In the above query, we have simply added another attribute condition in the ‘where’ clause, retaining the usage of the ‘Op.gte’ operator for our ‘loginCount’ condition.

Advanced Conditions Using Sequelize Methods

Let’s dive into a more complex situation. Suppose we need not only the login count and active status but also want to check if the last login date is within a specific time range. Sequelize allows us to build such complex queries too.

User.findAll({
  where: {
    loginCount: {
      [Op.gte]: minLogins
    },
    isActive: true,
    lastLoginDate: {
      [Op.gte]: someStartDate,
      [Op.lte]: someEndDate
    }
  }
});

Conclusion

In this tutorial, we explored how to utilize the ‘greater than or equal to’ operator in Sequelize.js. We looked at basic usage, combining conditions, and advanced condition setting using sequelize’s find methods. It’s important to note that Sequelize also takes care of parameter escaping and injection prevention, making it a secure way to query your database using dynamic values.