Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using scopes with create method in Sequelize

Tags:

sequelize.js

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?

like image 373
sgarza62 Avatar asked Aug 12 '26 13:08

sgarza62


1 Answers

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

like image 81
jacqbus Avatar answered Aug 14 '26 10:08

jacqbus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!