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:
class Project extends Model {}
Project.init({
// Attributes
}, {
defaultScope: {
where: {
active: true
}
},
scopes: {
deleted: {
where: {
deleted: true
}
},
activeUsers: {
include: [
{ model: User, where: { active: true }}
]
},
random () {
return {
where: {
someNumber: Math.random()
}
}
},
accessLevel (value) {
return {
where: {
accessLevel: {
[Op.gte]: value
}
}
}
}
sequelize,
modelName: 'project'
}
});
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:
SELECT * FROM projects WHERE active = true
The default scope can be removed by calling .unscoped()
, .scope(null)
, or by invoking another scope:
Project.scope('deleted').findAll(); // Removes the default scope
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):
activeUsers: {
include: [
{ model: User.scope('active')}
]
}