handsome
handsome

Reputation: 2432

using findByPk and WHERE condition in sequelize

In Sequelize I´m using findByPk but I also need to pass another condition

const options = {
    where: { role: 'admin' },
};

return models.User.findByPk(id, options)
    .then((user) => {...

But this query is retuning all users even if the role is not admin. I checked the SQL generated and I see SELECT * from User WHERE id = 1 but I don´t see the AND role = 'admin'. how to use findByPk and pass another condition?

thank you

Upvotes: 11

Views: 36329

Answers (1)

jknotek
jknotek

Reputation: 1864

You'll have to use findOne instead, and pass the primary key as a field in the where object:

return models.User.findOne({
  where: {
    id: id,
    role: 'admin', 
  },
})

The Sequelize documentation can be a little cluttered... But, the options argument in findByPk doesn't take the same values as the one in findOne. If you look closely at the documentation for findByPk, you'll see a note at the bottom that reads:

See: Model.findAll for a full explanation of options, Note that options.where is not supported.

Upvotes: 25

Related Questions