Sequelize model
Sequelize is a popular Node.js ORM (Object-Relational Mapping) library that simplifies interaction with relational databases like MySQL, PostgreSQL, SQLite, and others. A Sequelize model is essentially a representation of a database table in your application code, allowing you to interact with database records as JavaScript objects.
Defining a Model
A model in Sequelize is defined using thesequelize.define()
method or by extending theSequelize.Model
class. You specify the name of the model and the schema of the table (i.e., the columns and their data types).const { Sequelize, DataTypes, Model } = require('sequelize'); const sequelize = new Sequelize('database_name', 'username', 'password', { host: 'localhost', dialect: 'postgres', port: 5432, // The default port for PostgreSQL }); const User = sequelize.define( 'User', { // Model attributes are defined here firstName: { type: DataTypes.STRING, allowNull: false, }, lastName: { type: DataTypes.STRING, // allowNull defaults to true }, email: { type: DataTypes.STRING, allowNull: false, unique: true } }, { // Other model options sequelize, // pass the sequelize instance modelName: 'User' // Name of the model }, );
Attributes
Attributes correspond to columns in the database table. Each attribute has a name (the column name) and a type (e.g.,STRING
,INTEGER
,BOOLEAN
, etc.), along with additional options likeallowNull
,unique
,defaultValue
, etc.Instance Methods and Class Methods
Instance Methods: Methods that can be called on instances (rows) of the model.
Class Methods: Static methods that can be called directly on the model itself.
User.prototype.getFullName = function() { return `${this.firstName} ${this.lastName}`; }; User.findByEmail = async function(email) { return await User.findOne({ where: { email } }); };
Associations
Sequelize supports defining relationships between models, such ashasOne
,hasMany
,belongsTo
, andbelongsToMany
. These associations allow you to define relationships like one-to-many, many-to-many, etc.class Post extends Model {} Post.init({ title: { type: DataTypes.STRING, allowNull: false } }, { sequelize, modelName: 'Post' }); // Define associations User.hasMany(Post); Post.belongsTo(User);
CRUD Operations
Sequelize models allow you to perform common CRUD (Create, Read, Update, Delete) operations easily. Some examples,
i) Create: Create a new record in the table.const user = await User.create({ firstName: 'John', lastName: 'Doe', email: 'john.doe@example.com' });
ii) Read: Fetch records from the table.
const users = await User.findAll(); const user = await User.findByPk(1); // Find by primary key
iii) Update: Update existing records.
user.lastName = 'Smith'; await user.save();
iv) Delete: Remove records from the table.
await user.destroy();
Validation and Hooks
i) Validation: Sequelize supports built-in and custom validation for model attributes.
ii) Hooks: You can define hooks (also known as lifecycle events) that run at specific times in a model's lifecycle, such as before/after creation, updating, or deletion.
User.beforeCreate((user, options) => { user.email = user.email.toLowerCase(); });
Example of a Simple Model
const { Sequelize, DataTypes } = require('sequelize'); const sequelize = new Sequelize('sqlite::memory:'); const User = sequelize.define('User', { firstName: { type: DataTypes.STRING, allowNull: false }, lastName: { type: DataTypes.STRING }, email: { type: DataTypes.STRING, allowNull: false, unique: true } }, { // Options }); (async () => { await sequelize.sync({ force: true }); // Sync the model with the database const user = await User.create({ firstName: 'Jane', lastName: 'Doe', email: 'jane.doe@example.com' }); console.log(user.toJSON()); })();
Sequelize models are powerful tools for managing and interacting with your database in a structured and object-oriented manner, abstracting away the complexities of SQL and allowing you to work directly with JavaScript objects.