Expansion of models

Sequelize Models are ES6 classes. You can very easily add custom instance or class level methods.

  1. class User extends Model {
  2. // Adding a class level method
  3. static classLevelMethod() {
  4. return 'foo';
  5. }
  6. // Adding an instance level method
  7. instanceLevelMethod() {
  8. return 'bar';
  9. }
  10. }
  11. User.init({ firstname: Sequelize.STRING }, { sequelize });

Of course you can also access the instance's data and generate virtual getters:

  1. class User extends Model {
  2. getFullname() {
  3. return [this.firstname, this.lastname].join(' ');
  4. }
  5. }
  6. User.init({ firstname: Sequelize.STRING, lastname: Sequelize.STRING }, { sequelize });
  7. // Example:
  8. User.build({ firstname: 'foo', lastname: 'bar' }).getFullname() // 'foo bar'

Indexes

Sequelize supports adding indexes to the model definition which will be created during Model.sync() or sequelize.sync.

  1. class User extends Model {}
  2. User.init({}, {
  3. indexes: [
  4. // Create a unique index on email
  5. {
  6. unique: true,
  7. fields: ['email']
  8. },
  9. // Creates a gin index on data with the jsonb_path_ops operator
  10. {
  11. fields: ['data'],
  12. using: 'gin',
  13. operator: 'jsonb_path_ops'
  14. },
  15. // By default index name will be [table]_[fields]
  16. // Creates a multi column partial index
  17. {
  18. name: 'public_by_author',
  19. fields: ['author', 'status'],
  20. where: {
  21. status: 'public'
  22. }
  23. },
  24. // A BTREE index with an ordered field
  25. {
  26. name: 'title_index',
  27. using: 'BTREE',
  28. fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
  29. }
  30. ],
  31. sequelize
  32. });