Sequelize Introduction and Basic Usage
Installing Sequelize
To use Sequelize in your project, install Sequelize and the appropriate database driver. For MySQL:
npm install --save sequelize mysql2Initializing Sequelize
Create a Sequelize instance to connect to the database:
const { Sequelize } = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */
});Defining Models
Models represent database tables in Sequelize. Define attributes and their types:
const { DataTypes } = require('sequelize');
const User = sequelize.define('user', {
firstName: {
type: DataTypes.STRING,
allowNull: false
},
lastName: {
type: DataTypes.STRING
},
email: {
type: DataTypes.STRING,
unique: true,
allowNull: false
}
}, {
timestamps: false
});Synchronizing Models
Sync models with the database using the sync method, creating tables if they don’t exist:
sequelize.sync({ force: false }).then(() => {
console.log('Models synchronized with database.');
});Data Operations
Sequelize provides methods for Create, Read, Update, and Delete (CRUD) operations:
// Create a record
User.create({
firstName: 'John',
lastName: 'Doe',
email: 'john.doe@example.com'
}).then(user => {
console.log(user.toJSON());
});
// Read a record
User.findByPk(1).then(user => {
console.log(user.toJSON());
});
// Update a record
User.update({ firstName: 'Jane' }, {
where: { email: 'john.doe@example.com' }
}).then(([numberOfUpdatedRows]) => {
console.log(numberOfUpdatedRows + ' rows updated');
});
// Delete a record
User.destroy({
where: { email: 'john.doe@example.com' }
}).then(numberOfDeletedRows => {
console.log(numberOfDeletedRows + ' rows deleted');
});Associations
Sequelize supports defining associations like one-to-one, one-to-many, and many-to-many:
const Project = sequelize.define('project', {
// ...
});
User.hasMany(Project);
Project.belongsTo(User);Queries
Sequelize offers powerful querying capabilities, including conditional queries, sorting, pagination, and association queries:
// Conditional query
User.findOne({
where: { email: 'john.doe@example.com' }
}).then(user => {
console.log(user.toJSON());
});
// Sorting and pagination
User.findAll({
order: [['createdAt', 'DESC']],
limit: 10,
offset: 10
}).then(users => {
console.log(users.map(user => user.toJSON()));
});
// Association query
User.findOne({
include: [{
model: Project
}]
}).then(user => {
console.log(user.toJSON());
});Transactions
Sequelize supports transactions to ensure atomic operations:
sequelize.transaction(t => {
return User.create({ /* ... */ }, { transaction: t })
.then(user => {
return Project.create({ /* ... */, userId: user.id }, { transaction: t });
});
}).then(() => {
console.log('Transaction completed successfully.');
}).catch(err => {
console.error('Transaction failed:', err);
});



