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 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. 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. activeUsers: {
  2. include: [
  3. { model: User.scope('active')}
  4. ]
  5. }