Express insert values into MySQL database - mysql

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;

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;

why sequelize-cli is not loading config variables?

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.

Node js not connected with MySQL new created database

I am trying to connect NodeJS with MySQL database.I am using WAMP. It's connected only default database like "mysql"and"information_schema" but those databases i created not connect with NodeJs and given me following error.
Please let me know where i am going wrong.
Code
**Server.js**
----------
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const mysql = require("mysql");
app.use(bodyParser.json());
var connection = mysql.createConnection({
host : "localhost",
user : "root", //User Name
password : "", // No password
database : "techbiz", // Database Name
multipleStatements:true
});
connection.connect((err)=>{
if(!err)
{
console.log("Database connected ");
}
else{
console.log(err) }
})
// Initialize port
const PORT = process.env.PORT || 5000;
// send rquest to web page
app.get('/',(req,res) => res.send(`Automize Business Solution running on :${PORT}`));
app.listen(PORT,()=>console.log("Server is running"));
[Database][1]
**Error**
----------
Server is running
{ Error: ER_BAD_DB_ERROR: Unknown database 'techbiz'
at Handshake.Sequence._packetToError (K:\WebProjects\MySQL\abs-server\node_modules\mysql\lib\protocol\sequences\Sequence.js:47:14)
at Handshake.ErrorPacket (K:\WebProjects\MySQL\abs-server\node_modules\mysql\lib\protocol\sequences\Handshake.js:123:18)
at Protocol._parsePacket (K:\WebProjects\MySQL\abs-
at Socket.<anonymous> (K:\WebProjects\MySQL\abs-
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)
code: 'ER_BAD_DB_ERROR',
errno: 1049,
sqlMessage: 'Unknown database \'techbiz\'',
sqlState: '42000',
fatal: true }
[1]: https://i.stack.imgur.com/E9MSc.png
Thanks
i just change my wamp version and using MySQL 5.5.8 , and now same code working fine.
thanks

Node.js config file for mysql DB

I have a small issue when setting up my config file. I'm sure this is something simple but I don't see what is the problem.
I have my config file config.js under config/config.js
var databaseOptions = {
host : 'localhost',
database : 'test',
user : 'root',
password : 'root',
port : '8889'
};
module.exports = databaseOptions;
And then I use it in my model:
var config = require('../config/config.js');
var mysql = require('mysql');
var connection = mysql.createConnection(config.databaseOptions);
But it doesn't work ...
Instead I get an error : TypeError: Cannot read property 'host' of undefined
I also tried like this :
var connection = mysql.createConnection({
host : config.databaseOptions.host,
database : config.databaseOptions.database,
user : config.databaseOptions.user,
password : config.databaseOptions.password,
port : config.databaseOptions.port
});
... but I still get an undefined error.
Any idea ...?
You are exporting databaseOptions directly so you just need:
var databaseOptions = require('../config/config.js');
var connection = mysql.createConnection(databaseOptions);
If you want to use config.databaseOptions, you need to export:
var databaseOptions = {
host : 'localhost',
database : 'test',
user : 'root',
password : 'root',
port : '8889'
};
module.exports = {databaseOptions: databaseOptions} ;
or
module.exports.databaseOptions = {
host : 'localhost',
database : 'test',
user : 'root',
password : 'root',
port : '8889'
};
Then you can use:
var config = require('../config/config.js');
var connection = mysql.createConnection(config.databaseOptions);
The second way will be more flexible if you have more than one object you want to export from config.

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']
);