Sequelize Setup and Configuration

Understanding Sequelize Tools

Before diving into setup, let's understand the two main Sequelize tools at our disposal - think of them as different types of workshop tools, each with its specific purpose:

sequelize vs sequelize-cli

sequelize

Think of this as your main workbench - it's the core ORM engine that handles all database operations in your application code.


npm install sequelize
                    

sequelize-cli

This is like your toolbox of command-line utilities - helping you create, manage, and organize your database structure.


npm install -D sequelize-cli
                    

Customizing Your Workshop: The .sequelizerc File

The .sequelizerc file is like a blueprint for your workshop layout. It tells Sequelize where to find and store different types of files:


// .sequelizerc
const path = require('path');

module.exports = {
    'config': path.resolve('config', 'database.js'),
    'models-path': path.resolve('db', 'models'),
    'seeders-path': path.resolve('db', 'seeders'),
    'migrations-path': path.resolve('db', 'migrations')
};
                

Environment Variables: Your Project's Security Guard

Using environment variables is like having a secure vault for sensitive information. Instead of hardcoding database credentials, we store them safely:

.env file:


DB_USERNAME=myuser
DB_PASSWORD=mypassword
DB_DATABASE=mydatabase
DB_HOST=localhost
                

database.js configuration:


require('dotenv').config();

module.exports = {
    development: {
        username: process.env.DB_USERNAME,
        password: process.env.DB_PASSWORD,
        database: process.env.DB_DATABASE,
        host: process.env.DB_HOST,
        dialect: 'postgres'
    }
    // Add other environments (production, test) as needed
};
                

Common CLI Operations

Here are the essential Sequelize CLI commands you'll use regularly:


# Initialize Sequelize in your project
npx sequelize-cli init

# Create a new model and its migration
npx sequelize-cli model:generate --name User --attributes firstName:string,email:string

# Run pending migrations
npx sequelize-cli db:migrate

# Undo last migration
npx sequelize-cli db:migrate:undo

# Create a seed file
npx sequelize-cli seed:generate --name demo-users

# Run seeds
npx sequelize-cli db:seed:all
                

Practical Example: Setting Up a Blog Platform

Let's see how this all comes together in a real-world scenario:


blog-platform/
├── .env
├── .sequelizerc
├── config/
│   └── database.js
├── db/
│   ├── models/
│   ├── migrations/
│   └── seeders/
└── package.json
                

This structure is like organizing a library, where each folder has a specific purpose and contains related items. The separation makes it easier to maintain and scale your application.