I'm trying to connect the DataBase with Sequelize and NodeJS but an error happen and I can't connect to DB. Through inspection I see that the 'config' variable is null and 'config.use_env_variable' isn't constructed in "config/config.js".
Could someone please help me know what's wrong and how to fix it?
In the "models/index.js" file:
'use strict';
require('dotenv').config();
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};
if (config == null){
console.log("config is null");
} else {
console.log('config is not null ');
}
// create instance to Connect DB
let sequelize;
...
In the "config/config.json" file:
{
"development": {
"username": "root",
"password": null,
"database": "hoidanit",
"host": "127.0.0.1",
"dialect": "mysql"
},
"test": {
"username": "root",
"password": null,
"database": "database_test",
"host": "127.0.0.1",
"dialect": "mysql"
},
"production": {
"username": "root",
"password": null,
"database": "database_production",
"host": "127.0.0.1",
"dialect": "mysql"
}
}
And I have declared two variable in ".env" file:
PORT=8090
NODE_ENV=development
(Note that i am using Node.js v18.17.1, Sequelize v6.6.2 and Sequelize-cli v6.2.0).
"dependencies": {
"body-parser": "^1.19.0",
"dotenv": "^8.2.0",
"ejs": "^3.1.5",
"express": "^4.17.1",
"mysql2": "^2.2.5",
"sequelize": "^6.6.2"
},
"devDependencies": {
"@babel/core": "^7.12.10",
"@babel/node": "^7.12.10",
"@babel/preset-env": "^7.12.10",
"nodemon": "^2.0.7",
"sequelize-cli": "^6.2.0"
}
I tried add variable 'use_env_variable' in "config.js" but nothing happened.
When using Sequelize with NodeJS, the setup generally expects a JavaScript file for the config. But in your case, it looks like you're supplying a
JSONfile, and as such, you're not able to include theuse_env_variablesetting.In your
config/config.js, rename it and refactor it from beingJSONto being an exported Javascript object.The
use_env_variableis just for making it easier forsequelizeunderstand, if it can't get it from the info you provided before