Scopes

Scopes are used to help you reuse code. You can define commonly used queries, specifying options such as where, include, limit, etc.

This guide concerns model scopes. You might also be interested in the guide for association scopes, which are similar but not the same thing.

Definition

Scopes are defined in the model definition and can be finder objects, or functions returning finder objects - except for the default scope, which can only be an object:

  1. class Project extends Model {}
  2. Project.init({
  3. // Attributes
  4. }, {
  5. defaultScope: {
  6. where: {
  7. active: true
  8. }
  9. },
  10. scopes: {
  11. deleted: {
  12. where: {
  13. deleted: true
  14. }
  15. },
  16. activeUsers: {
  17. include: [
  18. { model: User, where: { active: true } }
  19. ]
  20. },
  21. random() {
  22. return {
  23. where: {
  24. someNumber: Math.random()
  25. }
  26. }
  27. },
  28. accessLevel(value) {
  29. return {
  30. where: {
  31. accessLevel: {
  32. [Op.gte]: value
  33. }
  34. }
  35. }
  36. }
  37. sequelize,
  38. modelName: 'project'
  39. }
  40. });

You can also add scopes after a model has been defined by calling YourModel.addScope. This is especially useful for scopes with includes, where the model in the include might not be defined at the time the other model is being defined.

The default scope is always applied. This means, that with the model definition above, Project.findAll() will create the following query:

  1. SELECT * FROM projects WHERE active = true

The default scope can be removed by calling .unscoped(), .scope(null), or by invoking another scope:

  1. await Project.scope('deleted').findAll(); // Removes the default scope
  1. SELECT * FROM projects WHERE deleted = true

It is also possible to include scoped models in a scope definition. This allows you to avoid duplicating include, attributes or where definitions. Using the above example, and invoking the active scope on the included User model (rather than specifying the condition directly in that include object):

  1. // The `activeUsers` scope defined in the example above could also have been defined this way:
  2. Project.addScope('activeUsers', {
  3. include: [
  4. { model: User.scope('active') }
  5. ]
  6. });

Usage

Scopes are applied by calling .scope on the model definition, passing the name of one or more scopes. .scope returns a fully functional model instance with all the regular methods: .findAll, .update, .count, .destroy etc. You can save this model instance and reuse it later:

  1. const DeletedProjects = Project.scope('deleted');
  2. await DeletedProjects.findAll();
  3. // The above is equivalent to:
  4. await Project.findAll({
  5. where: {
  6. deleted: true
  7. }
  8. });

Scopes apply to .find, .findAll, .count, .update, .increment and .destroy.

Scopes which are functions can be invoked in two ways. If the scope does not take any arguments it can be invoked as normally. If the scope takes arguments, pass an object:

  1. await Project.scope('random', { method: ['accessLevel', 19] }).findAll();

Generated SQL:

  1. SELECT * FROM projects WHERE someNumber = 42 AND accessLevel >= 19

Merging

Several scopes can be applied simultaneously by passing an array of scopes to .scope, or by passing the scopes as consecutive arguments.

  1. // These two are equivalent
  2. await Project.scope('deleted', 'activeUsers').findAll();
  3. await Project.scope(['deleted', 'activeUsers']).findAll();

Generated SQL:

  1. SELECT * FROM projects
  2. INNER JOIN users ON projects.userId = users.id
  3. WHERE projects.deleted = true
  4. AND users.active = true

If you want to apply another scope alongside the default scope, pass the key defaultScope to .scope:

  1. await Project.scope('defaultScope', 'deleted').findAll();

Generated SQL:

  1. SELECT * FROM projects WHERE active = true AND deleted = true

When invoking several scopes, keys from subsequent scopes will overwrite previous ones (similarly to Object.assign), except for where and include, which will be merged. Consider two scopes:

  1. YourMode.addScope('scope1', {
  2. where: {
  3. firstName: 'bob',
  4. age: {
  5. [Op.gt]: 20
  6. }
  7. },
  8. limit: 2
  9. });
  10. YourMode.addScope('scope2', {
  11. where: {
  12. age: {
  13. [Op.gt]: 30
  14. }
  15. },
  16. limit: 10
  17. });

Using .scope('scope1', 'scope2') will yield the following WHERE clause:

  1. WHERE firstName = 'bob' AND age > 30 LIMIT 10

Note how limit and age are overwritten by scope2, while firstName is preserved. The limit, offset, order, paranoid, lock and raw fields are overwritten, while where is shallowly merged (meaning that identical keys will be overwritten). The merge strategy for include will be discussed later on.

Note that attributes keys of multiple applied scopes are merged in such a way that attributes.exclude are always preserved. This allows merging several scopes and never leaking sensitive fields in final scope.

The same merge logic applies when passing a find object directly to findAll (and similar finders) on a scoped model:

  1. Project.scope('deleted').findAll({
  2. where: {
  3. firstName: 'john'
  4. }
  5. })

Generated where clause:

  1. WHERE deleted = true AND firstName = 'john'

Here the deleted scope is merged with the finder. If we were to pass where: { firstName: 'john', deleted: false } to the finder, the deleted scope would be overwritten.

Merging includes

Includes are merged recursively based on the models being included. This is a very powerful merge, added on v5, and is better understood with an example.

Consider the models Foo, Bar, Baz and Qux, with One-to-Many associations as follows:

  1. const Foo = sequelize.define('Foo', { name: Sequelize.STRING });
  2. const Bar = sequelize.define('Bar', { name: Sequelize.STRING });
  3. const Baz = sequelize.define('Baz', { name: Sequelize.STRING });
  4. const Qux = sequelize.define('Qux', { name: Sequelize.STRING });
  5. Foo.hasMany(Bar, { foreignKey: 'fooId' });
  6. Bar.hasMany(Baz, { foreignKey: 'barId' });
  7. Baz.hasMany(Qux, { foreignKey: 'bazId' });

Now, consider the following four scopes defined on Foo:

  1. Foo.addScope('includeEverything', {
  2. include: {
  3. model: Bar,
  4. include: [{
  5. model: Baz,
  6. include: Qux
  7. }]
  8. }
  9. });
  10. Foo.addScope('limitedBars', {
  11. include: [{
  12. model: Bar,
  13. limit: 2
  14. }]
  15. });
  16. Foo.addScope('limitedBazs', {
  17. include: [{
  18. model: Bar,
  19. include: [{
  20. model: Baz,
  21. limit: 2
  22. }]
  23. }]
  24. });
  25. Foo.addScope('excludeBazName', {
  26. include: [{
  27. model: Bar,
  28. include: [{
  29. model: Baz,
  30. attributes: {
  31. exclude: ['name']
  32. }
  33. }]
  34. }]
  35. });

These four scopes can be deeply merged easily, for example by calling Foo.scope('includeEverything', 'limitedBars', 'limitedBazs', 'excludeBazName').findAll(), which would be entirely equivalent to calling the following:

  1. await Foo.findAll({
  2. include: {
  3. model: Bar,
  4. limit: 2,
  5. include: [{
  6. model: Baz,
  7. limit: 2,
  8. attributes: {
  9. exclude: ['name']
  10. },
  11. include: Qux
  12. }]
  13. }
  14. });
  15. // The above is equivalent to:
  16. await Foo.scope([
  17. 'includeEverything',
  18. 'limitedBars',
  19. 'limitedBazs',
  20. 'excludeBazName'
  21. ]).findAll();

Observe how the four scopes were merged into one. The includes of scopes are merged based on the model being included. If one scope includes model A and another includes model B, the merged result will include both models A and B. On the other hand, if both scopes include the same model A, but with different options (such as nested includes or other attributes), those will be merged recursively, as shown above.

The merge illustrated above works in the exact same way regardless of the order applied to the scopes. The order would only make a difference if a certain option was set by two different scopes - which is not the case of the above example, since each scope does a different thing.

This merge strategy also works in the exact same way with options passed to .findAll, .findOne and the like.