Elements of Sequelize Models Migrations and Seeds

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.

Understanding Models

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.

Defining a Model


// 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;
    

Understanding Migrations

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.

Creating a Migration


npx sequelize-cli migration:generate --name create-books
    

Example Migration File


// 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');
  }
};
    

Understanding Seeds

Seeding allows you to **populate your database with sample data**. This is useful for testing or setting up a development environment.

Creating a Seed File


npx sequelize-cli seed:generate --name seed-books
    

Example Seed File


// 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, {});
  }
};
    

How Models, Migrations, and Seeds Work Together

When building an application:

Final Thoughts

Understanding **Sequelize models, migrations, and seeds** is key to managing databases efficiently. By following these principles, you ensure a **scalable, maintainable, and testable** application.