Using the where option in Sequelize methods

Sequelize where option accepts an object describing the WHERE clause to add to your generated SQL query.

For example, suppose you have a table named Users with the following details:

id  firstName 

 1  John

await User.findAll({

 where: { firstName: “John” },

});

We can also create more complex conditions by adding operators from Sequelize Op object.

For example, you can create a WHERE … IN condition using the Op.in operator as follows:

const { Op } = require(“sequelize”);

await User.findAll({

 where: {

  firstName: { [Op.in]: [“John”, “Arun”] },

 },

});

Alternatively, you can also omit the Op.in operator for a WHERE … IN clause and rewrite it as follows:

await User.findAll({

 where: {

  firstName: [“John”, “Arun”],

 },

});

When you need to add the AND operator into the WHERE clause, you can add multiple properties to the where option.

The example below adds a condition for both the id AND firstName columns:

const { Op } = require(“sequelize”);

await User.findAll({

 where: {

  id: { [Op.lte]: 2 },

  firstName: { [Op.notIn]: [“John”, “Arun”] },

 },

});

We can use the where option with Sequelize findAll() or findOne(), destroy(), and update() methods.

Leave a comment

Your email address will not be published. Required fields are marked *