Sequelize is a powerful **JavaScript Object Relational Mapping (ORM)** library that allows developers to interact with SQL databases using JavaScript. Understanding the key elements of Sequelize—**models, migrations, and seeds**—is essential for efficient database management.
A **model** in Sequelize is a JavaScript **class** that acts as a **blueprint** for a database table. It defines what **columns** exist, their **data types**, and any **relationships** with other tables.
// models/book.js
const { Sequelize, Model, DataTypes } = require('sequelize');
const sequelize = new Sequelize('sqlite::memory:');
class Book extends Model {}
Book.init({
title: DataTypes.STRING,
author: DataTypes.STRING,
publishedYear: DataTypes.INTEGER
}, { sequelize, modelName: 'book' });
module.exports = Book;
A **migration** is a JavaScript file that defines **database schema changes** over time. Instead of manually altering database tables, you use migrations to track and apply changes systematically.
npx sequelize-cli migration:generate --name create-books
// migrations/20230101010101-create-books.js
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.createTable('Books', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true,
allowNull: false
},
title: {
type: Sequelize.STRING,
allowNull: false
},
author: {
type: Sequelize.STRING,
allowNull: false
},
publishedYear: {
type: Sequelize.INTEGER
}
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.dropTable('Books');
}
};
Seeding allows you to **populate your database with sample data**. This is useful for testing or setting up a development environment.
npx sequelize-cli seed:generate --name seed-books
// seeders/20230101020202-seed-books.js
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.bulkInsert('Books', [
{ title: '1984', author: 'George Orwell', publishedYear: 1949 },
{ title: 'Brave New World', author: 'Aldous Huxley', publishedYear: 1932 }
]);
},
down: async (queryInterface, Sequelize) => {
await queryInterface.bulkDelete('Books', null, {});
}
};
When building an application:
Understanding **Sequelize models, migrations, and seeds** is key to managing databases efficiently. By following these principles, you ensure a **scalable, maintainable, and testable** application.