why sequelize-cli is not loading config variables? - mysql

I tried searching for the answer, closest question i got was Sequelize CLI Not Finding Env Variables.
I compared my code and it was exactly like the answer provided, then just to debug i edited config file to set values manually instead of reading from .env but sequelize-cli still gives same error
ERROR: SequelizeDatabaseError: Access denied for user ''#'localhost' to database 'dbname'
at Query.formatError (/home/name/Documents/nodejs/project/db/node_modules/sequelize/lib/dialects/mysql/query.js:265:16)
at Query.run (/home/name/Documents/nodejs/project/db/node_modules/sequelize/lib/dialects/mysql/query.js:77:18)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async /home/name/Documents/nodejs/project/db/node_modules/sequelize/lib/sequelize.js:619:16
at async Object.exports.handler (/home/name/Documents/nodejs/project/db/node_modules/sequelize-cli/lib/commands/database.js:49:7)
Here is my config.js file
require("dotenv").config();
console.log(process.env.NODE_ENV, "it is being loaded correctly");
const config = {
development: {
username: "mysql",
password: "",
database: "dbname",
host: "localhost",
port: "3306",
dialect: "mysql",
dialectOptions: {
charset: "utf8mb4",
},
},
production: {
username: "mysql",
password: "",
database: "dbname",
host: "localhost",
port: "3306",
dialect: "mysql",
dialect: "mysql",
dialectOptions: {
charset: "utf8mb4",
},
},
};
console.log(config);
module.exports = config;
and lastly here is .sequelizerc file
const path = require('path');
module.exports = {
'config': path.resolve('config', 'config.js')
}
Funny thing is this project was working perfectly on my last computer (macos) and my server(ubuntu) but i am facing this issue with ubuntu desktop. AFAIK it should not be an operating system problem.
here is models/index.js
"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;
console.log(env);
const config = require(__dirname + "/../config/config")[env];
const db = {};
console.log("config check", config);
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
);
}
fs.readdirSync(__dirname)
.filter((file) => {
return (
file.indexOf(".") !== 0 && file !== basename && file.slice(-3) === ".js"
);
})
.forEach((file) => {
const model = require(path.join(__dirname, file))(
sequelize,
Sequelize.DataTypes
);
db[model.name] = model;
});
Object.keys(db).forEach((modelName) => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
UPDATE 1:
I have tried to connect to database programmatically and get same error.
original: Error: Access denied for user ''#'localhost' to database 'dbname'
at Packet.asError (/home/user/Documents/nodejs/project/db/node_modules/mysql2/lib/packets/packet.js:712:17)
at ClientHandshake.execute (/home/user/Documents/nodejs/project/db/node_modules/mysql2/lib/commands/command.js:28:26)
at Connection.handlePacket (/home/user/Documents/nodejs/project/db/node_modules/mysql2/lib/connection.js:425:32)
at PacketParser.onPacket (/home/user/Documents/nodejs/project/db/node_modules/mysql2/lib/connection.js:75:12)
at PacketParser.executeStart (/home/user/Documents/nodejs/project/db/node_modules/mysql2/lib/packet_parser.js:75:16)
at Socket.<anonymous> (/home/user/Documents/nodejs/project/db/node_modules/mysql2/lib/connection.js:82:25)
at Socket.emit (events.js:400:28)
at addChunk (internal/streams/readable.js:290:12)
at readableAddChunk (internal/streams/readable.js:265:9)
at Socket.Readable.push (internal/streams/readable.js:204:10) {
code: 'ER_DBACCESS_DENIED_ERROR',
errno: 1044,
sqlState: '42000',
sqlMessage: "Access denied for user ''#'localhost' to database 'dbname'"

A couple of shots in the dark: If you try to connect with a blank password you need to set the password param to null in the connection configuration:
const sequelize = new Sequelize('database', 'username', null, {
dialect: 'mysql'
})
Also, as mentioned in a comment, it looks like it can't set your username correctly, so it turns out as an empty string ('') in the error msg.
Maybe you have switched around username and password in the config object for Sequelize so the empty password becomes the username?
Will update this answer if I get better ideas when you show the connection code :)
EDIT 1:
Seems to be something fishy about your config in new Sequelize(process.env[config.use_env_variable], config);
It should have four parameters, here you have added the username and password into the config object. There should be three string params (or null) and one config object, four in total.

Related

Access denied for user 'root#localhost'

I am currently working on a homework based on ORM. I finished my code however when I start my server, I get a access denied. I checked my credentials for my env file and its correct. I have attached the message from gitbash as well, my connection code to gain access to the database, and an env example of the credentials that are required. enter image description here
DB_NAME='ecommerce_db'
DB_USER=''
DB_PASSWORD=''
require('dotenv').config();
const Sequelize = require('sequelize');
const sequelize = process.env.JAWSDB_URL
? new Sequelize(process.env.JAWSDB_URL)
: new Sequelize(process.env.DB_NAME, process.env.DB_USER, process.env.DB_PW, {
host: 'localhost',
dialect: 'mysql',
dialectOptions: {
decimalNumbers: true,
},
});
module.exports = sequelize;

I can't connect to mysql database using process.env.variable

my config.env file
PORT=5000
DB_HOST='localhost'
DB_PORT=3306
DB_USER='root'
DB_PASSWORD='fast'
DB_NAME='hms'
my dbconnect file(in same directory as config.env file)
I cannot connect using process.env but if I directly type values like I have did in commented code then it will connect to database. Also if I console.log values of process.env.anyvariable then I will get the correct value of env variable but if i assign it to some variable like suppose const variable=process.env.DB_HOST then it will be undefined in console.log. It is throwing me this error
code: 'ER_ACCESS_DENIED_ERROR',
errno: 1045,
sqlMessage: "Access denied for user ''#'localhost' (using password: NO)",
sqlState: '28000',
fatal: true
const mysql = require("mysql")
const dotenv = require("dotenv")
dotenv.config({ path: './config.env' });
const connection = mysql.createConnection({
host: process.env.DB_HOST,
port: process.env.DB_PORT,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME
})
// const connection = mysql.createConnection({
// host: 'localhost',
// port: 3306,
// user: 'root',
// password: 'fast',
// database: 'hms'
// })
connection.connect( (err) => {
if (err){
console.log(err)
}
else
{
console.log("Database connected!")
}
})
my /config/config.env is not in the parent directoy so instead of
dotenv.config({ path: './config.env' });
write
dotenv.config({ path: __dirname + '/config.env' });

Unhandled rejection SequelizeDatabaseError: No database selected

I'm using sequelize in my Express.js application with MySQL.
All database credentials are stored in .env file and are correct:
DATABASE_NAME= mydb
DATABASE_USERNAME= root
DATABASE_PASSWORD= pass
DATABASE_HOST= localhost
DATABASE_PORT= 3306
database.js file:
require('dotenv').config();
const Sequelize = require('sequelize');
module.exports = new Sequelize(
process.env.DATABAST_NAME,
process.env.DATABASE_USERNAME,
process.env.DATABASE_PASSWORD,
{
port: process.env.DATABASE_PORT,
host: process.env.DATABASE_HOST,
dialect: 'mysql'
}
);
In user model:
const Sequelize = require('sequelize');
const db = require('../config/database');
module.exports = db.define('user', {
username: {
type: Sequelize.STRING,
unique: true,
primaryKey: true
},
email: {
type: Sequelize.STRING,
unique: true
},
password: {
type: Sequelize.STRING
},
}, {
freezeTableName: true,
timestamps: false
});
user.findAll().then(data=>{
console.log(data)
});
Database 'mydb' has only one table 'user', with the application start, I got an error:
Executing (default): SELECT `username`, `email`, `password` FROM `user` AS `user`;
Unhandled rejection SequelizeDatabaseError: No database selected
at Query.formatError (C:\Users\me\WebstormProjects\Backend\node_modules\sequelize\lib\dialects\mysql\query.js:241:16)
at Query.handler [as onResult] (C:\Users\me\WebstormProjects\Backend\node_modules\sequelize\lib\dialects\mysql\query.js:48:23)
at Query.execute (C:\Users\me\WebstormProjects\Backend\node_modules\mysql2\lib\commands\command.js:30:14)
at Connection.handlePacket (C:\Users\me\WebstormProjects\Backend\node_modules\mysql2\lib\connection.js:449:32)
at PacketParser.Connection.packetParser.p [as onPacket] (C:\Users\me\WebstormProjects\Backend\node_modules\mysql2\lib\connection.js:72:12)
at PacketParser.executeStart (C:\Users\me\WebstormProjects\Backend\node_modules\mysql2\lib\packet_parser.js:75:16)
at Socket.Connection.stream.on.data (C:\Users\me\WebstormProjects\Backend\node_modules\mysql2\lib\connection.js:79:25)
at Socket.emit (events.js:189:13)
at addChunk (_stream_readable.js:284:12)
at readableAddChunk (_stream_readable.js:265:11)
at Socket.Readable.push (_stream_readable.js:220:10)
at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
I tried to test .env file with below code, and everything is readable:
var config = require('dotenv').config();
console.log(config)
I tried to add database name in front of 'user', in db.defind(), and i got the same issue.
Please, if you have any suggestions, let me know.
Your database name is empty when you're initializing Sequelize. It looks like you spelled DATABASE wrong.
module.exports = new Sequelize(
process.env.DATABAST_NAME, // <--- This is an empty string or null.
process.env.DATABASE_USERNAME,
process.env.DATABASE_PASSWORD,
{
port: process.env.DATABASE_PORT,
host: process.env.DATABASE_HOST,
dialect: 'mysql'
}
);
Install dotenv package from npm with command:
npm install dotenv
Require dotenv in your main.ts file which is located inside the 'src' folder by adding the below lines:
import * as dotenv from "dotenv";
dotenv.config();
Run your project once again.

Error: Access denied for user ''#'localhost' (using password: NO)

I'm trying out db migrations with MySQL and Knex.
When I run the command knex migrate:latest, I get
ER_ACCESS_DENIED_ERROR: Access denied for user ''#'localhost' (using password: NO)
I've tried adding a password on the codebase (to '123' and 'NO'), though what confuses me most is that even as I have user: "root" in my database file, the error gives an empty string as the user...
I share what I imagine are the pertinent files:
// mysql_db.js
const knex = require('knex')({
client: 'mysql',
connection: {
host: 'localhost',
user: 'root',
password: '',
database: 'SQL_Data',
},
});
module.exports = knex;
// knexfile.js
const path = require('path');
module.exports = {
development: {
client: 'mysql',
connection: {
filename: '/server/SQL/mysql_db',
},
migrations: {
directory: path.join(__dirname, '/server/SQL/migrations'),
},
seeds: {
directory: path.join(__dirname, '/server/SQL/seeds'),
},
},
};
//knex.js
const environment = proces.env.NODE_ENV || 'development';
const config = require('../../knexfile.js')[environment];
module.exports = require(knex)('config');
// "migration definition"
exports.up = (knex, Promise) => knex.schema.createTable('sql_table', ((table) => {
table.increments();
table.string('name').notNullable();
table.string('email').notNullable();
table.string('description').notNullable();
table.string('url').otNullable();
}));
exports.down = (knex, Promise) => knex.schema.dropTable('sql_table');
As error message say you are trying to login with invalid credentials user whose name is empty string doesn't exist in DB.
This means your configuration is wrong. you have some strange segment in your node-mysql driver configuration, which tries to refer other file, which exports initialized knex instance
client: 'mysql',
connection: {
filename: '/server/SQL/mysql_db'
}
That is just plain wrong. Correct format for knexfile is pretty much the same that is used to create knex instance, except that knexfile supports also selecting the profile according to NODE_ENV environment variable.
const path = require('path');
module.exports = {
development: {
client: 'mysql',
connection: {
host: 'localhost',
user: 'root',
password: '',
database: 'SQL_Data',
},
migrations: {
directory: path.join(__dirname, '/server/SQL/migrations'),
},
seeds: {
directory: path.join(__dirname, '/server/SQL/seeds'),
},
},
};
In your mysql_db you might like to do something like this to init knex to
be able to use the same config:
const knex = require('knex')(
require('knexfile')[process.env.NODE_ENV || 'development']
);

Express insert values into MySQL database

PROBLEM SOLVED. Please look below.
I'm new into Express and NodeJS, ditched Laravel and PHP.
What I want to do is to be able to add a record into MySQL database, but I am not able to connect the dots. I'm following this tutorial series :
http://eddyjs.com/bookshelf-js/
http://eddyjs.com/using-mysql-with-bookshelf-js-part-2-using-the-database/
There are two db variables, I couldn't understand how to use them.
Here's the error.
Cannot read property 'extend' of undefined
TypeError: Cannot read property 'extend' of undefined
at Object. (/Applications/MAMP/htdocs/myapp/myapp/models/User.js:5:20)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)
I installed all dependencies via npm, everything is ok.
"dependencies": {
"body-parser": "~1.13.2",
"bookshelf": "^0.8.2",
"cookie-parser": "~1.3.5",
"debug": "~2.2.0",
"express": "~4.13.1",
"jade": "~1.11.0",
"jquery": "^2.1.4",
"knex": "^0.8.6",
"morgan": "~1.6.1",
"mysql": "^2.9.0",
"serve-favicon": "~2.3.0"
}
I hold my models in models folder.
User.js
var db = require('./db');
var User = db.Model.extend({
tableName: 'users'
});
module.exports = User;
routes/index.js
router.get('/add', function(req,res,next) {
var User = require('../models/User');
new User({
'name': 'Edwin',
'pet': 'dog'
})
.save()
.then(function (newUser) {
console.log('user created!', newUser);
});
});
db.js (database connection should be opened once, right? So it has to live here)
var knex = require('knex')({
client: 'mysql',
connection: {
host : 'localhost',
user : 'root',
password : 'root',
port : 8889,
database : 'databasename',
charset : 'utf8'
}
});
var bookshelf = require('bookshelf')(knex);
var User = bookshelf.Model.extend({
tableName: 'users'
});
If I understand correctly the directory structure of your project, you have the routes directory next to the models directory, right?
if this is the case, you need to change the require in routes/index.js to use ../, so it will get to the right location:
var User = require('../models/User');
Problem solved when I change db.js. The key is the module.exports = db; part, I guess.
var knex = require('knex')({
client: 'mysql',
connection: {
host : 'localhost',
user : 'root',
password : 'root',
port : 8889,
database : 'bosluk',
charset : 'utf8'
}
});
var db = require('bookshelf')(knex);
module.exports = db;