Modeling a table

A model is a class that extends Sequelize.Model. Models can be defined in two equivalent ways. The first, with Sequelize.Model.init(attributes, options):

  1. const Model = Sequelize.Model;
  2. class User extends Model {}
  3. User.init({
  4. // attributes
  5. firstName: {
  6. type: Sequelize.STRING,
  7. allowNull: false
  8. },
  9. lastName: {
  10. type: Sequelize.STRING
  11. // allowNull defaults to true
  12. }
  13. }, {
  14. sequelize,
  15. modelName: 'user'
  16. // options
  17. });

Alternatively, using sequelize.define:

  1. const User = sequelize.define('user', {
  2. // attributes
  3. firstName: {
  4. type: Sequelize.STRING,
  5. allowNull: false
  6. },
  7. lastName: {
  8. type: Sequelize.STRING
  9. // allowNull defaults to true
  10. }
  11. }, {
  12. // options
  13. });

Internally, sequelize.define calls Model.init.

The above code tells Sequelize to expect a table named users in the database with the fields firstName and lastName. The table name is automatically pluralized by default (a library called inflection is used under the hood to do this). This behavior can be stopped for a specific model by using the freezeTableName: true option, or for all models by using the define option from the Sequelize constructor.

Sequelize also defines by default the fields id (primary key), createdAt and updatedAt to every model. This behavior can also be changed, of course (check the API Reference to learn more about the available options).

Changing the default model options

The Sequelize constructor takes a define option which will change the default options for all defined models.

  1. const sequelize = new Sequelize(connectionURI, {
  2. define: {
  3. // The `timestamps` field specify whether or not the `createdAt` and `updatedAt` fields will be created.
  4. // This was true by default, but now is false by default
  5. timestamps: false
  6. }
  7. });
  8. // Here `timestamps` will be false, so the `createdAt` and `updatedAt` fields will not be created.
  9. class Foo extends Model {}
  10. Foo.init({ /* ... */ }, { sequelize });
  11. // Here `timestamps` is directly set to true, so the `createdAt` and `updatedAt` fields will be created.
  12. class Bar extends Model {}
  13. Bar.init({ /* ... */ }, { sequelize, timestamps: true });

You can read more about creating models in the Model.init API Reference, or in the sequelize.define API reference.