'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
      },


Solution 1:[1]

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?

Solution 2:[2]

Did you forget to add this at the top ?

require('dotenv').config()

Solution 3:[3]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 saqsham
Solution 3 Tyler2P