Sling Academy
Home/Node.js/How to Use Migrations and Sync in Sequelize.js

How to Use Migrations and Sync in Sequelize.js

Last updated: December 29, 2023

Overview

Migrations are an essential part of modern database management in web development, allowing developers to track and share changes to the database schema. Sequelize.js, a popular ORM for Node.js, comes with robust support for migrations, providing a systematic way to create, modify, and share database schemas. In this tutorial, we’ll cover the basics of setting up migrations and syncing your models with the database using Sequelize.

Setting Up Sequelize

First, ensure that you have Sequelize CLI installed globally:

npm install -g sequelize-cli

Next, initialize Sequelize in your project:

sequelize init

This will create the necessary folders and files, including a config folder that holds your database configuration.

Creating a Migration

To create a new migration file, use the following command:

sequelize migration:create --name create-users

This creates a new file in your ‘migrations’ folder, with boilerplate up and down methods for forward and reverse transactions.

Defining a Migration

Edit the newly created migration file to define the schema for the ‘Users’ table:

module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.createTable('Users', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      name: {
        allowNull: false,
        type: Sequelize.STRING
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: async (queryInterface, Sequelize) => {
    await queryInterface.dropTable('Users');
  }
};

Running Migrations

To apply migrations to your database, you’ll run:

sequelize db:migrate

Sequelize will execute the ‘up’ method in your migration files to update your database schema.

Model Syncing

Syncing models with the database ensures that the defined models in your application match your database schema. To sync, simply call `sync` on your model:

User.sync(); // Syncs just the User model
sequelize.sync(); // Syncs all models

However, use this with caution in a production environment since it can lead to data loss if the model definitions do not match the migration files.

Advanced Migration Operations

Complex alterations to your database can also be handled with Sequelize migrations. For instance, adding a column:

queryInterface.addColumn(
  'Users', // table name
  'email', // new field name
  {
    type: Sequelize.STRING,
    allowNull: false
  }
);

Or changing a column:

queryInterface.changeColumn(
  'Users',
  'name',
  {
    type: Sequelize.STRING,
    allowNull: true
  }
);

Remember to create and run a new migration for each change to avoid conflicts.

Using Migrations for Rollbacks

If something goes wrong after a migration, you can use the `db:migrate:undo` command to revert the last migration:

sequelize db:migrate:undo

To undo all migrations up to a certain one, you can use:

sequelize db:migrate:undo --to XXXXXXXXXXXXXX-create-users.js

Replace XXXXXXXXXXXXXX with the timestamp in the name of the migration file you wish to revert to.

Conclusion

Migrations are a powerful feature of Sequelize.js that allow for more controlled schema changes and collaborations within development teams. Combined with model syncing, Sequelize provides an elegant solution for managing your application’s data layer. Remember to use these tools wisely, especially in production environments, to keep your data safe and your schema consistent.

Next Article: How to Backup and Restore a Database in Sequelize.js

Previous Article: What is Eager Loading in Sequelize.js?

Series: Sequelize.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates