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:
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).
bashnpm 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
Run the following command to initialize Sequelize in your project:
bashnpx sequelize-cli init
This command will create a config
, models
, migrations
, and seeders
directory in your project.
Update the config/config.json
file with your database connection details.
Create a Sequelize model to represent your database table. For example, let's say you want to create a Users
table:
bashnpx sequelize-cli model:generate --name User --attributes firstName:string,lastName:string,email:string
This command will generate a model file in the models
directory.
Now, you can run the migration to create the Users
table in your database:
bashnpx sequelize-cli db:migrate
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:
bashnpx 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.
Run the migration again to apply the changes to your database:
bashnpx sequelize-cli db:migrate
To undo the last migration, you can use:
bashnpx sequelize-cli db:migrate:undo
To see the list of available commands, you can run:
bashnpx 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.