- Sequelize is an ORM (Object-Relational Mapping) for Node.js, which allows for the mapping of object syntax in JavaScript to database schemas. When you create a model in Sequelize, you define the structure of your table in the database, including the columns and their data types. Sequelize then provides a wealth of functionalities such as creating, retrieving, updating, and deleting records on your behalf.
- When you define a model in Sequelize, you typically specify the model's attributes and their data types. This definition tells Sequelize how to map the model to the database table.
const User = sequelize.define('User', {
// Model attributes are defined here
firstName: {
type: DataTypes.STRING,
allowNull: false
},
lastName: {
type: DataTypes.STRING
// allowNull defaults to true
}
}, {
// Other model options go here
});
- In this example, 'User' is a model with two attributes: 'firstName' and 'lastName'. The 'DataTypes.STRING' indicates that these fields should be stored in the database as strings. The 'allowNull' field is used to specify whether the field can be null.
- When you define and synchronize your model with the database, Sequelize automatically adds some default attributes to your table if you don't explicitly disable this feature:
- id: A primary key column, which is automatically added to your models as an auto-incrementing integer unless you specify otherwise. This serves as a unique identifier for each record.
- 'createdAt' and 'updatedAt': Timestamp fields that Sequelize manages automatically. 'createdAt' is the time when the record was inserted into the table, and 'updatedAt' is the time when the record was last updated. These fields are extremely useful for tracking when records are added or modified.
- To disable these default fields, you can set the timestamps option to false in the model definition:
{
timestamps: false
// Other options...
}
- Additionally, if you enable the 'paranoid' option by setting it to 'true', Sequelize adds a 'deletedAt' attribute to your model, which is used to mark records as deleted without actually removing them from the database. This is known as "soft deletion."
{
paranoid: true
// Other options...
}
- In this case, instead of removing a record from the database, Sequelize sets the 'deletedAt' field with the current timestamp. Queries generated by Sequelize automatically ignore records marked as deleted unless explicitly told not to.
- This system of automatically managing 'id', 'createdAt', `updatedAt`, and optionally 'deletedAt' simplifies the process of managing common fields across your tables and ensures consistency in how these typical aspects are handled.
No comments:
Post a Comment