Sling Academy
Home/Node.js/How to use Sequelize CLI

How to use Sequelize CLI

Last updated: December 29, 2023

Overview

Sequelize Command Line Interface (CLI) is a powerful tool that facilitates database operations and workflow management for applications using the Sequelize ORM. This tutorial aims to guide you through the basic to advanced usage of Sequelize CLI with practical code examples. By the end of this guide, you’ll be equipped with the knowledge to leverage Sequelize in your Node.js projects effectively.

Sequelize CLI is a package that provides command line functionality for managing your Sequelize-based projects. It allows you to perform tasks like database migrations, model generation, and seeding directly from the terminal, simplifying the development process significantly.

This tutorial assumes you have a basic understanding of Node.js, npm, and relational databases.

Getting Started with Sequelize CLI

The first step in utilizing the Sequelize CLI is to install it. You must have Node.js and npm already set up in your environment. Install Sequelize CLI globally using the following npm command:

npm install -g sequelize-cli

After installation, you can access the CLI by invoking sequelize in your terminal. Verify that the installation was successful by checking the version number:

sequelize --version

If you see a version number output, you’re all set to proceed.

Project Initialization

Start by initializing a new Sequelize project using the sequelize init command. This will create necessary configuration files and folders in your project directory:

sequelize init

You will see the following directories and files created:

  • config/config.json: Contains database configuration.
  • migrations: Folder to store migration files.
  • models: Folder to store model files.
  • seeders: Folder to store seed files.

It’s a good practice to review and adjust the contents of config/config.json to suit your database configurations.

Creating Models and Migrations

With the project initialized, you can create models and their corresponding migrations. Here’s a command to generate a model named User with some basic attributes:

sequelize model:create --name User --attributes firstName:string,lastName:string,email:string

This command will generate a model file in the models folder and a migration file in the migrations folder, which you can then modify if necessary.

Database Migrations

Migrations are essential for managing database schema changes. Apply your migrations using the command:

sequelize db:migrate

If you need to revert a migration, you can do so with:

sequelize db:migrate:undo

To revert all migrations, run:

sequelize db:migrate:undo:all

Seeding the Database

Database seeding populates your database with initial data. To create a seed file, run:

sequelize seed:generate --name demo-user

Edit the seed file with the data you want to insert into the database. To run the seed, use:

sequelize db:seed:all

To undo seed operations, you can use:

sequelize db:seed:undo

Or for undoing a specific seed:

sequelize db:seed:undo --seed name-of-seed-as-in-file

Advanced Usage

Sequelize CLI also allows for more advanced usage such as setting up multiple configurations for different environments, writing custom SQL in migrations, and using the programmatic API to integrate with custom scripts.

Multiple environments can be managed through the config.json file by having separate keys for development, test, and production, each with their respective database configurations.

When it comes to writing custom SQL in migrations, Sequelize CLI gives you the option to execute raw queries:

module.exports = { up: async (queryInterface, Sequelize) => { await queryInterface.sequelize.query('YOUR RAW SQL HERE'); }, down: async (queryInterface, Sequelize) => { await queryInterface.sequelize.query('REVERT RAW SQL HERE'); } };

Moreover, with the programmatic API, you’re able to write JavaScript code that uses the Sequelize CLI within your application:

const { Sequelize, Migration } = require('sequelize-cli')

Conclusion

This tutorial provided an in-depth look into the Sequelize CLI, from initialization and model creation to advanced data management and configuration techniques. By mastering these fundamentals and more complex operations, you are now equipped to handle the database aspects of your Node.js applications with finesse and confidence. Remember to always test your migrations and seeds in a development environment before applying them to production, and make use of sequelize’s logging capabilities to troubleshoot any issues that arise.

Next Article: Understanding GROUP BY in Sequelize.js

Previous Article: How to use regular expressions in Sequelize.js queries

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