'Using scopes with create method in Sequelize

Sequelize scopes allow users to define reusable queries on the model. You can define a defaultScope, as well as named scopes. I got these working for find, update, and findAll, but not for create.

From the docs:

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.

Is it possible to apply a scope to the create method, so the returned instance is limited to certain attributes?



Solution 1:[1]

I also came here looking for an answer to this question, but until there is a more appropriate one, I wanted to share my solution (which is not used in production so far).

Well, I used the afterCreate hook rather than the scope like this:

afterCreate: (user, opts) => {
  // Prevent from return password after create user
  delete user.dataValues.password;
}

I would like to point out right away that this is not a proven solution, but it may be useful as a starting point :)

P.S .: sequelize 6.12.4

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 jacqbus