3

I'm following this tutorial Using PostgreSQL and Sequelize to persist our data on medium, and right now I'm stuck at the db:migrate. it's returning this error

Sequelize CLI [Node: 12.1.0, CLI: 5.4.0, ORM: 5.8.2]

Loaded configuration file "config.json".
Using environment "development".

ERROR: Error parsing url: undefined

as you can see I'm using NodeJS version 12.1.0 and Sequelize CLI version 5.4.0 and Sequelize version 5.8.2 and all of them were the latest version.

and before running sequelize db:migrate, I'm running this command first SET DATABASE_URL=postgresql://[user[:password]@][netlocation][:port][/dbname] and it does not returns any error.

but it's returning error after I ran db:migrate

I already tried to find the problem, but I can't found the answer yet. Here is my ./Models/Index.js file.

'use strict';

require('dotenv').config();

import { readdirSync } from 'fs';
import { basename as _basename, join } from 'path';
import Sequelize from 'sequelize';
const basename = _basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../../config.json')[env];
const db = {};

let sequelize;
if (config.use_env_variable) {
  sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
  sequelize = new Sequelize(config.database, config.username, config.password, config);
}

readdirSync(__dirname)
  .filter(file => {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
  })
  .forEach(file => {
    const model = sequelize['import'](join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

export default db;

if you realize I just changed it to ES6 format which change some codes, but before I change it to ES6, it doesn't work either. and for all the rest of the files I following the tutorial.

Here are the files that I think have a connection:

.env

DATABASE_URL=postgres://postgres:admin@localhost:5432/test_app

.sequelizerc

const path = require('path');

module.exports = {
  "config": path.resolve('./config.json'),
  "models-path": path.resolve('./app/Models'),
  "migrations-path": path.resolve('./migrations')
};

config.json

{
  "development": {
    "use_env_variable": "DATABASE_URL"
  },
  "test": {
    "use_env_variable": "DATABASE_URL"
  },
  "production": {
    "use_env_variable": "DATABASE_URL"
  }
}

If there are some files that I haven't included yet please tell me, and please help me to fix find the solution for this problem. Thank you

OS: Windows 10

5
  • do you have gitbash? Commented May 7, 2019 at 19:35
  • yes I have, and I'm using VScode as well @aitchkhan Commented May 8, 2019 at 3:14
  • try the below solution then Commented May 8, 2019 at 4:48
  • Where you able to solve the problem? I am having the same Issue Commented Apr 30, 2021 at 4:19
  • @nnam4x Yes before I am able to solve the problem, but I forgot how to solve it as it's already been too long and I'm not using NodeJS anymore. Sorry! Commented Apr 30, 2021 at 8:54

3 Answers 3

4
+25

Basically you are unable to set environment variable DATABASE_URL successfully.

I am not a Windows guy, but this should do your job.

If you are using GitBash, then it is as simple as:

export DATABASE_URL=postgres://postgres@localhost:5432/database_name

and after that:

node_modules/.bin/sequelize db:migrate

EDIT:

I am not sure how to set this variable in gitbash and cmd. Here is an alternate.

in config/config.json

"development": {
    "username": "postgres"
    "password": "postgres",
    "database": "your_db_here",
    "host": "127.0.0.1",
    "dialect": "postgres"
},

update these variables according to your postgres db.

and run:

node_modules/.bin/sequelize db:migrate
Sign up to request clarification or add additional context in comments.

5 Comments

So this line export DATABASE_URL=postgres://postgres@localhost:5432/database_name is for set the URL to environment variables on PC ? if that's the case, is there any wildcard settings for it? so I can use it for another project as well? because from what I think it will only work for a certain project because the database name
This does not set the environment variable on your PC. This only sets the environment variable for the current shell session. You can do that separately for another project in its own shell session.
Hi, unfortunately it doesn't work, Git bash doesnt recognized the export command
Thanks for your answer, but I already using it because I was stuck with my question, but still thanks for helping me :smile:
this will allow you to run migration atleast. I will try to solve the environment variable issue.
2
  1. You cannot fetch values at runtime inside config.json. It has to be static.
  2. You should either use config.json or env variables or roll your own like mentioned in another answer.

To use env variables, you will eschew config.json. Instead, in models/index.js, set

if (config.use_env_variable) {
  sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
  sequelize = new Sequelize(config.database, config.username, config.password, config);
}

to

sequelize = new Sequelize(process.env.DATABASE_URL)

Comments

0

AFAIK Sequelize migrations are a different beast than the normal sequelize workflow.

It is reading config/config.json when it loads - so you cannot use system environment variables - it has to be a static json file.

What I do in my projects, is having my config.js file making sure the config file is up to date with whatever settings I have.

I do this when the main program starts and also in package.json as follows:

(make sure to add npm-run-all to your package.json)

  "scripts": {
    "config": "node src/config.js",
    "_migrate": "sequelize db:migrate",
    "_migrate:status": "sequelize db:migrate:status",
    "_migrate:undo": "sequelize db:migrate:undo",
    "_seed": "sequelize db:seed:all",
    "migrate": "npm-run-all config _migrate",
    "migrate:status": "npm-run-all config _migrate:status",
    "migrate:undo": "npm-run-all config _migrate:undo",
    "seed": "npm-run-all config _seed"
  },

config.js simply does something similar to this at the end of the file:

// Export sequelize config/config.json for easy compatibality with sequelize-cli
const filepath = path.resolve(__dirname, '../../config');
const filename = path.join(filepath, 'config.json');

fs.ensureDir(filepath)
    .then(() => fs.writeFileSync(filename, JSON.stringify(sequelizeConfig, 2) + '\n'))
    .catch((err) => console.error(`Failed to write config: ${err}`));

sequelizeConfig is should be the fully generated sequelize config object. You can also have a generic one like you have now, and build upon it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.