Sequelize conditional shorthands

Sequelize Conditional Shorthands

If you are working with Sequelize ORM for Node.js, you might come across situations where you need to define some conditional statements in your queries. Sequelize provides some shorthand operators to make this process easier.

Using Sequelize's Conditional Shorthands

Sequelize provides the following shorthand operators:

  • $eq
  • $ne
  • $gte
  • $gt
  • $lte
  • $lt
  • $not
  • $between
  • $notBetween
  • $in
  • $notIn
  • $like
  • $notLike
  • $iLike
  • $notILike
  • $regexp
  • $notRegexp
  • $iRegexp
  • $notIRegexp

Here is an example of how to use these operators:


const { Op } = require('sequelize');
const users = await User.findAll({
  where: {
    age: {
      [Op.gt]: 18
    },
    name: {
      [Op.startsWith]: 'J'
    }
  }
});

In the above example, we are using the $gt and $startsWith operators to find all users whose age is greater than 18 and whose name starts with the letter 'J'.

Multiple Conditions

You can also use multiple conditions by nesting them inside an array:


const users = await User.findAll({
  where: {
    [Op.or]: [
      {
        age: {
          [Op.gt]: 18
        }
      },
      {
        name: {
          [Op.startsWith]: 'J'
        }
      }
    ]
  }
});

In the above example, we are using the $or operator to find all users whose age is greater than 18 or whose name starts with the letter 'J'.

Conclusion

Sequelize's conditional shorthands provide an easy way to define complex conditions in your queries. By using these operators, you can write more concise and readable code.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe