Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sequalize migration with dotenv

I am saving my database config in dotenv file.

I am using sequelize migration which has a config.json file in config folder:

{
 "development": {
    "username": "root",
    "password": null,
    "database": "test",
    "host": "127.0.0.1",
    "dialect": "postgres"
  },
  ....
}

Since I have configuration in dotenv do I have to convert it to js file:

require('dotenv').config({ silent: env === 'production'})

const devConfig = {
  dialect: 'postgres',
  host: process.env.DB_HOST || 'localhost',
  port: process.env.DB_PORT || 5432,
  database: process.env.DB_NAME || '',
  username: process.env.DB_USER || 'postgres',
  password: process.env.DB_PASSWORD || '',
  migrationStorageTableName: 'migrations'
};

module.exports = {
  development: devConfig,
  production: devConfig
};

but how can I run the the migration, which the config is not JSON?

node_modules/.bin/sequelize db:migrate --config config/config.js
like image 320
Alvin Avatar asked Aug 21 '17 06:08

Alvin


People also ask

Does Dotenv work in production?

The reason you dont use it in production is that in production you would usually be running the application in a docker container or a dedicated server, either of which, you wouldnt need to worry about setting conflicting environment variables.

How do I add a Dotenv to my project?

To use DotEnv, first install it using the command: npm i dotenv . Then in your app, require and configure the package like this: require('dotenv'). config() .


1 Answers

  1. Rename config.json to config.js and call your environment variables inside.
module.exports = {
  development: {
    username: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    host: process.env.DB_HOST,
    dialect: 'postgres',
    logging: false,
  },
  test: {
    username: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    host: process.env.DB_HOST,
    dialect: 'postgres',
    logging: false,
  },
  production: {
    username: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    host: process.env.DB_HOST,
    dialect: 'postgres',
    logging: false,
    pool: {
      max: 5,
      min: 0,
      acquire: 30000,
      idle: 10000,
    },
  },
};
  1. Create a .sequelizerc file with the following:
'use strict';

require('dotenv').config();    // don't forget to require dotenv
const path = require('path');

module.exports = {
  'config': path.resolve('config', 'config.js'),
  'models-path': path.resolve('models'),
  'seeders-path': path.resolve('seeders'),
  'migrations-path': path.resolve('migrations'),
};
  1. Run sequelize db:migrate
like image 159
moeabdol Avatar answered Oct 27 '22 01:10

moeabdol