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)
:
const Model = Sequelize.Model;
class User extends Model {}
User.init({
// attributes
firstName: {
type: Sequelize.STRING,
allowNull: false
},
lastName: {
type: Sequelize.STRING
// allowNull defaults to true
}
}, {
sequelize,
modelName: 'user'
// options
});
Alternatively, using sequelize.define
:
const User = sequelize.define('user', {
// attributes
firstName: {
type: Sequelize.STRING,
allowNull: false
},
lastName: {
type: Sequelize.STRING
// allowNull defaults to true
}
}, {
// options
});
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.
const sequelize = new Sequelize(connectionURI, {
define: {
// The `timestamps` field specify whether or not the `createdAt` and `updatedAt` fields will be created.
// This was true by default, but now is false by default
timestamps: false
}
});
// Here `timestamps` will be false, so the `createdAt` and `updatedAt` fields will not be created.
class Foo extends Model {}
Foo.init({ /* ... */ }, { sequelize });
// Here `timestamps` is directly set to true, so the `createdAt` and `updatedAt` fields will be created.
class Bar extends Model {}
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.