tksilicon
tksilicon

Reputation: 4426

Sequelize Migrate Not Recognising Dotenv

I am able to run migrate command when I specify the database name, user and password directly. But when I provide with env variable/value. It says no database selected. I have installed npm i dotenv

npx sequelize-cli db:migrate

dotenv is required.

require('dotenv').config();
    module.exports = {
      development: {
        username: process.env.DB_USER,
        password: process.env.DB_PASS,
        database: process.env.DB_NAME,
        host: process.env.DB_HOST,
        dialect: 'mysql',
        logging: false
      },
      test: {
        username: process.env.DB_USER,
        password: process.env.DB_PASS,
        database: process.env.DB_NAME,
        host: process.env.DB_HOST,
        dialect: 'mysql',
        logging: false
      },
      production: {
        use_env_variable: 'DATABASE_URL'
      }
    };

I have the following in .env file thus:

DB_USER=root
DB_PASS= 
DB_NAME=road_rescue_dev
DB_HOST=127.0.0.1

This works

development: {
        username: "root",
        password: "",
        database: road_rescue_dev,
        host: process.env.DB_HOST,
        dialect: 'mysql',
        logging: false
      },

Upvotes: 2

Views: 2717

Answers (4)

OMTBuzzinga
OMTBuzzinga

Reputation: 1

Maybe try to specify the path of .env in the dotenv's config. Like:

require('dotenv').config({path: 'your/path/to/.env'});

Upvotes: 0

Soham Godbole
Soham Godbole

Reputation: 1

Please check if NODE_ENV variable exist either in package.json or .env file. Sequelize migration picks environment from .env file.

Upvotes: 0

byyoung
byyoung

Reputation: 397

I got the same issue before. I figured out I have to

  1. require('dotenv').config() in the config file (just like you did)
  2. set .sequelizerc in the root directory like below
  3. set .sequelie file to point config, migrations, models, seeds directory from root directory
  4. and you should run npx seuqlie-cli db:migrate form root directory.

for some reason, if I run npx seuqlie-cli db:migrate from sequleize directory, it does not read dotenv variables.

I'm still figuring out why, but it works

this is my directory looks like enter image description here

my .sequlizerc file

const path = require('path')

module.exports={
    config: path.resolve('src/sequelize/config','config.js'),
    'migrations-path': path.resolve('src/sequelize/migrations'),
    'seeders-path': path.resolve('src/sequelize/seeders'),
    'models-path': path.resolve('src/sequelize/models')
}

Also posted question about this Sequelize migration doesnot read dotenv variable if I don't run it from root directory. why?

Upvotes: 1

saqsham
saqsham

Reputation: 69

Did you forget to add this at the top ?

require('dotenv').config()

Upvotes: 1

Related Questions