'Is there a difference between findOne and findByPk in Sequelize?

Provided that you're looking for something based on its primary key and don't want to include any additional options, does it matter whether you use findOne or findByPk? Would the performance be the same?



Solution 1:[1]

Model.findByPk() use Model.findOne() internally, you can see it from v6.19.0/src/model.js#L1933. Both of these methods are a shortcut.

In the end, both methods call the more general Model.findAll() method, look v6.19.0/src/model.js#L1968.

Both of them just do some parameter verification and create where clause options that have a negligible impact on performance.

The only difference is the usage.

Model.findByPk(1) is equivalent to Model.findOne({primaryKey: 1}), you need to specify the primary key by yourself.

Solution 2:[2]

Under the hood, there is no difference between passing a pk to findOne or using findByPk, i.e the performance is the same.

It's just an abstraction that sequelize gives in order to get a much readable code.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Naor Levi