Sequelize is one of the most popular Node.js Object Relational Mapping (ORM) libraries that offers a great way to interact with databases, alongside powerful features such as object associations, transactions, migrations, and more.
The Sequelize Command Line Interface (CLI) provides powerful command-line tools to make development tasks easier and faster. It allows you to perform common tasks such as creating and running migrations, seeding your database with data, and generating model and migration files with minimal effort.
In this article, we'll explore the most common Sequelize CLI commands along with some code examples.
Prerequisites
Before diving into the Sequelize CLI, make sure you have the following installed on your machine:
- Node.js
- Sequelize CLI
Once you have everything installed, we can get started by creating a new Sequelize project.
Creating a New Sequelize Project
To create a new Sequelize project, open up your terminal and navigate to the directory where you want to create your project. Then, run the following commands:
mkdir my-project
cd my-project
npm init
Once you've executed the above commands, you can install Sequelize as a dependency by running the following command:
npm install sequelize
Now that we have Sequelize installed, we need to install the Sequelize CLI as a dev dependency:
npm install --save-dev sequelize-cli
After that, we need to initialize Sequelize in our project by running the following command:
npx sequelize-cli init
This command creates a number of files and folders in your project directory, including:
- a database folder to store your SQL scripts and database configuration file
- a config folder to store your Sequelize configuration file
- a models folder to store your Sequelize model files
- a migrations folder to store your database migration files
Now that we have our project initialized, let's look at some of the most popular Sequelize CLI commands.
Creating a model
A model represents a table in your database, and it's used to define the structure of the data that you'll be working with. To create a new model using Sequelize CLI, you can run the following command:
npx sequelize-cli model:generate --name User --attributes firstName:string,lastName:string,email:string
In this example, we're creating a model called User with three attributes: firstName, lastName, and email. The command generates a new user model under the models folder, along with a corresponding migration file in the migrations folder.
Running a migration
Migrations allow you to modify your database schema over time, and Sequelize CLI provides a simple way to manage migrations. To run a migration, you can run the following command:
npx sequelize-cli db:migrate
This command runs all the pending migrations, applying any changes to the database schema.
Rolling back a migration
Sometimes you may need to roll back a migration if you've made a mistake or need to undo a change. To do this, you can run the following command:
npx sequelize-cli db:migrate:undo
This command reverts the last migration that was applied to the database.
Generating a seed file
Sometimes it's necessary to pre-populate your database with data. Sequelize CLI provides an easy way to create seed files that can populate your database with initial data. To generate a seed file, you can run the following command:
npx sequelize-cli seed:generate --name demo-user
This command generates a new seed file under the seeds folder.
Running seeders
Once you have your seed data, you can run the following command to populate your database:
npx sequelize-cli db:seed:all
This command runs all the seeders in the seeds folder and populates the database with the initial data.
Undoing seeders
If you need to revert your seeders, you can run the following command:
npx sequelize-cli db:seed:undo:all
This command undoes all the seeders that were run on the database.
Conclusion
The Sequelize CLI is a powerful tool that can help you to manage your database-related tasks with ease. In this article, we covered some of the most common commands, including creating a model, running a migration, generating a seed file, running seeders, and undoing seeders. By using Sequelize CLI, you can save time and effort on common development tasks, freeing up your time to focus on building great applications.
let's dive deeper into each of the topics we covered in the previous article.
Creating a Model
In Sequelize, a model is a representation of a table in the database. It defines the structure of the data and allows you to interact with the table in a more object-oriented manner.
The npx sequelize-cli model:generate
command generates a new model file under the /models
directory. Let's break down the command:
npx
is a tool that allows you to run executable npm packages without installing them globally.sequelize-cli
is the package name for the Sequelize CLI.model:generate
is the command we want to run. It generates a new model file.--name User
specifies the name of the model. You can replaceUser
with any name you want.--attributes firstName:string,lastName:string,email:string
defines the attributes of the model. In this example, we're creating aUser
model with three attributes:firstName
,lastName
, andemail
.
After running the command, you'll see two new files in the /models
directory: user.js
and index.js
. The user.js
file contains the definition for the User
model, while index.js
exports all the models you define in the /models
directory.
Running a Migration
A migration is a way to modify the structure of the database schema over time. Sequelize allows you to create and run migrations with ease.
The npx sequelize-cli db:migrate
command runs any pending migrations. It applies any changes to the database schema.
Once you've created a migration file, you can run the migration by executing the npx sequelize-cli db:migrate
command.
Let's take a look at an example migration file:
'use strict';
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.createTable('Users', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
firstName: {
type: Sequelize.STRING
},
lastName: {
type: Sequelize.STRING
},
email: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.dropTable('Users');
}
};
The migration file defines two methods: up
and down
. The up
method is responsible for creating the table, while the down
method is responsible for undoing the changes made in the up
method.
In this example, we're creating a Users
table with four columns: id
, firstName
, lastName
, and email
. The createdAt
and updatedAt
columns are automatically created by Sequelize.
Generating a Seed File
Seed files are used to populate your database with data. Sequelize allows you to create seed files with the npx sequelize-cli seed:generate
command.
After running the command, you'll see a new file in the /seeders
directory with a name like 20210621123456-demo-user.js
. The name of the file includes a timestamp to ensure that the seeders are executed in the correct order.
Here's an example seed file:
'use strict';
const {v4: uuidv4} = require('uuid');
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.bulkInsert('Users', [
{
id: uuidv4(),
firstName: 'John',
lastName: 'Doe',
email: 'john.doe@example.com',
createdAt: new Date(),
updatedAt: new Date()
},
{
id: uuidv4(),
firstName: 'Jane',
lastName: 'Doe',
email: 'jane.doe@example.com',
createdAt: new Date(),
updatedAt: new Date()
}
], {});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.bulkDelete('Users', null, {});
}
};
This seed file populates the Users
table with two new records. The seed data is defined in the up
method of the seeder, and the down
method deletes the seed data.
Running Seeders
You can run seeders with the npx sequelize-cli db:seed:all
command. This command runs all the seeders in the /seeders
directory and populates the database with the initial data.
Undoing Seeders
If you want to undo the seeders, you can use the npx sequelize-cli db:seed:undo:all
command. This command undoes all the seeders that were previously run on the database.
Conclusion
Sequelize CLI provides a powerful set of tools to manage your database schema, migrations, and seed data. With the model:generate
, db:migrate
, seed:generate
, and db:seed:all
commands, you can easily create models, modify database schemas, and populate your database with initial data. These tools save you valuable time and make it easier to manage your database schema over time.
Popular questions
- What is a Sequelize model, and how do you create one with Sequelize CLI?
A Sequelize model is a representation of a table in the database that defines the structure of the data and allows you to interact with the table in a more object-oriented manner. You can create a model with Sequelize CLI using the command npx sequelize-cli model:generate --name User --attributes firstName:string,lastName:string,email:string
.
- What is a database migration, and how do you run one using Sequelize CLI?
A database migration is a way to modify the structure of the database schema over time. You can create and run migrations with Sequelize CLI using the npx sequelize-cli db:migrate
command. This command runs any pending migrations and applies any changes to the database schema.
- How do you generate a seed file with Sequelize CLI, and what is it used for?
You can generate a seed file with Sequelize CLI using the npx sequelize-cli seed:generate
command. A seed file is used to populate your database with initial data.
- How do you run seeders using Sequelize CLI, and what do they do?
You can run seeders using Sequelize CLI using the npx sequelize-cli db:seed:all
command. Seeders are used to populate your database with initial data.
- How do you undo seeders using Sequelize CLI?
You can undo seeders using Sequelize CLI using the npx sequelize-cli db:seed:undo:all
command. This command undoes all the seeders that were previously run on the database.
Tag
Sequelizeutorial