How to use the Sequelize ORM for database migrations in a Node.js application



Image not found!!

Sequelize is a popular Object-Relational Mapping (ORM) library for Node.js, and it provides a powerful set of features for working with databases. Migrations in Sequelize are a way to version-control your database schema and apply changes over time. Here's a step-by-step guide on how to use Sequelize for database migrations in a Node.js application:

Step 1: Install Sequelize and a Database Driver

Make sure you have Node.js installed on your machine. Create a new Node.js project if you haven't already, and then install Sequelize and a database driver of your choice (e.g., PostgreSQL, MySQL, SQLite).

bash
npm install sequelize sequelize-cli pg # for PostgreSQL # or npm install sequelize sequelize-cli mysql2 # for MySQL # or npm install sequelize sequelize-cli sqlite3 # for SQLite

Step 2: Initialize Sequelize

Run the following command to initialize Sequelize in your project:

bash
npx sequelize-cli init

This command will create a config, models, migrations, and seeders directory in your project.

Step 3: Configure Database Connection

Update the config/config.json file with your database connection details.

Step 4: Create a Model

Create a Sequelize model to represent your database table. For example, let's say you want to create a Users table:

bash
npx sequelize-cli model:generate --name User --attributes firstName:string,lastName:string,email:string

This command will generate a model file in the models directory.

Step 5: Run Migrations

Now, you can run the migration to create the Users table in your database:

bash
npx sequelize-cli db:migrate

Step 6: Modify the Model

If you need to make changes to your database schema, modify the generated model file in the models directory, and then create a new migration file using:

bash
npx sequelize-cli migration:generate --name modify-users

Edit the newly generated migration file in the migrations directory to define the changes you want to make.

Step 7: Apply the Changes

Run the migration again to apply the changes to your database:

bash
npx sequelize-cli db:migrate

Additional Tips:

  • To undo the last migration, you can use:

    bash
    npx sequelize-cli db:migrate:undo
  • To see the list of available commands, you can run:

    bash
    npx sequelize-cli --help
  • Make sure to check the Sequelize documentation for more advanced features and options: Sequelize Migrations.

That's it! You've successfully set up Sequelize for database migrations in your Node.js application.