mvc with node/express and mysql - mysql

I'm getting confused. All the tutorials I see with mySql end up with something like this:
in models/dbconnection.js
var mysql = require('mysql');
port = process.env.PORT || 3333;
if (port == 3333) {
var connection = mysql.createConnection({
host: 'localhost',
port: 3306,
user: 'root',
password: 'root',
database: 'nameDataBase',
insecureAuth: true
});
} else {
console.log("Error");
}
connection.connect();
module.exports = connection;
And then in routes/user.js
...
router.delete("/:id", verifyToken, (req, res) => {
const newLocal = "DELETE FROM login_user WHERE id = ?";
connection.query(newLocal, [req.params.id], (err,rows,fields) => {
if (err) {
res.sendStatus(500);
return;
}
console.log(rows.affectedRows);
res.status(200).send({delete: rows});
});
});
module.exports = router;
model and controller aren't getting mixed here? If tomorrow I want to change the type of database, I have to make changes in the model and in the routes. Shouldn't I make functions such as getAllUsersBlaBla(params) in something like models/user.js and then call it from routes/user.js ?

I agree. There shouldn't be any database queries in the router, which is considered part of the controller in MVC.
The model should provide wrapper functions around database queries that can be called from the controller.
A lot of node apps (and probably tutorials) will choose simplicity rather than modularity, that's why you would see code like that.

Related

errno: 1203, code: 'ER_TOO_MANY_USER_CONNECTIONS' in nodejs mysql code?

Hello Everyone,
I'm a beginner in Node.js Mysql. I have connected to Node.js with mysql. While starting the Node.js server, I got the error like " code: 'ER_TOO_MANY_USER_CONNECTIONS', " further I will attach the mysql db connection code below. Any type of help would be appreciated. Thanks in advance...
var db = mysql.createPool({
host: 'xxxxxxxxxxxxxxxxx',
port: 'xxx',
user: 'xxxx',
password: 'xxx',
database: 'xxx'
});
db.getConnection((err, tempConn) => {
if (err) {
console.log(err);
}
else {
tempConn.release();
console.log('Mysql Connected');
}
});
module.exports={db};
If you're creating a pool you don't need to use getConnection. There is a shortcut that allows you to use it directly. If you do use getConnection you must follow it with a query, then you may release the connection. Your example is missing a query.
Here is a helpful template for using a pool config:
// in your application initialization file such as app.js
//
// other require items here as well like express maybe?
//
const mysql = require('mysql');
const connection = mysql.createPool({
connectionLimit: 10,
host: process.env.DB_HOST || '127.0.0.1',
user: process.env.DB_USER || 'local_user',
password: process.env.DB_PASSWORD || 'local_password',
database: process.env.DB_NAME || 'local_database',
multipleStatements: true,
charset: 'utf8mb4' // necessary if you might need support for emoji characters
});
connection.on('connection', function (connection) {
// handy for testing
console.log('Pool id %d connected', connection.threadId);
});
connection.on('enqueue', function () {
// handy for testing
console.log('Waiting for available connection slot');
});
global.db = connection;
//
// other app setup stuff here like app.set, app.engine, app.use, module.exports = app and all that good stuff
//
// later…
// everywhere else in your app, use the global db variable when running queries
// ../new_users.js or similar maybe?
const _create_user = (user_payload) => {
db.query(
'INSERT INTO users SET ?', user_payload, function(error, results, fields) {
if (error) throw error;
console.log(results);
});
}
// maybe we are in a module that has access to
// the request object so we can use something
// that has come via POST
//
// here is a manual object as a placeholder…
let new_user = {
first_name: 'John',
last_name: 'Smith',
email: 'j.smith#example.com',
password: 'keyboard_cat'
}
_create_user(new_user);

How to fetch data from MySQL database with Node

I'm new to react, developing a recipe-app and I got a problem while displaying the data from MySQL database. The connection was created successfully, however, I'm not sure about how to reach the data. When I run node server.js in my terminal, I get "connected", When I visit the localhost:8080/users, I get "This site can't be reached" message and in my terminal:
`events.js:187
throw er; // Unhandled 'error' event
^
Error: Cannot enqueue Handshake after already enqueuing a Handshake.`
I'm a little stuck here. Anyone knows a solution or direct me a little bit? Thank you so much!
Server.js
const express = require('express');
const app = express();
const PORT = 8080;
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'recipe_app'
});
connection.connect((err) => {
if (err) throw err;
console.log('Connected!');
});
//creating route for the app
app.get('/users', (req, res) => {
connection.connect();
connection.query('SELECT * from users', function(err, rows, fields) {
if (!err) {
res.send(JSON.stringify(rows));
} else {
console.log('Error while performing Query.');
}
});
connection.end();
});
//making server listen to request
app.listen(PORT, () => {
console.log(`Server running at : http://localhost:${PORT}/`);
});
You're trying to reconnect to mysql after the connection has been established.
See my comments on the code below
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'recipe_app'
});
connection.connect((err) => { // This creates the connection
if (err) throw err;
console.log('Connected!');
});
And when you're trying to resolve your GET routes, you're trying to connect again
//creating route for the app
app.get('/users', (req, res) => {
connection.connect(); // reconnect here
Since you're using the default connection method, trying to connect to an already established connection will cause the driver to throw a Handshake error.
If you want to re-use the connection, store it in a variable and then re-use it in other part of your code.
If you want to manage multiple connections instead, I suggest you to look at createPool instead.
Try removing the connection.connect() and connection.end() from app.get

Node.js: how to apply util.promisify to mysql pool in its simplest way?

I saw another thread and and the post Create a MySQL Database Middleware with Node.js 8 and Async/Await, but right now I just want to use the util.promisify in the most simplest and straight-forward way that I can think, applying it to mysql connection-pool. Regarding the Node.js documentation, bellow is my code snipet:
exports.genAdminCfg = function (app) {
let sql = 'SELECT * FROM nav_tree;';
let pool = require('mysql').createPool({
host: 'localhost',
user: 'root',
password: 'mysql',
database: 'n4_ctrl',
connectionLimit: 4,
multipleStatements: true
});
/* --- Works fine without "promisify":
pool.query(sql, function (err, rows) {
if (err) {
console.log(err);
return err;
} else {
app.locals.adminCfg = genCfg(rows);
app.locals.adminCfg.dbConnectionPool = pool;
}
});
*/
/* --- Does not worke with "promisify":
TypeError: Cannot read property 'connectionConfig' of undefined
at Pool.query (/usr/home/zipper/node/n4.live/node_modules/mysql/lib/Pool.js:194:33)
*/
require('util').promisify(pool.query)(sql).then(function (rows) {
app.locals.adminCfg = genCfg(rows);
app.locals.adminCfg.dbConnectionPool = pool;
}, function (error) {
console.log(error);
});
};
The code I commented-out works fine without promisify. But the similar code next to it with promisify does not work and shows TypeError: Cannot read property 'connectionConfig' of undefined. What's wrong with the code?
node version = v8.1.4
It always should be expected that a method relies on the context, unless proven otherwise.
Since pool.query is a method, it should be bound to correct context:
const query = promisify(pool.query).bind(pool);
This may be unneeded because there are promise-based alternatives for most popular libraries that could make use of promises, including mysql.
Before sharing my example, here are greater details about bind method and async function.
const mysql = require('mysql')
const { promisify } = require('util')
const databaseConfig = {
connectionLimit : 10,
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME
}
const pool = mysql.createPool(databaseConfig)
const promiseQuery = promisify(pool.query).bind(pool)
const promisePoolEnd = promisify(pool.end).bind(pool)
const query = `select * from mock_table limit 1;`
const result = await promiseQuery(query) // use in async function
promisePoolEnd()

Nodejs/Express Ajax call to MySQL

I am looking for a sample and how to make ajax call to get data from MySQL for Nodejs/Express projects.
I have database connection established in app.js file. That's starts when node is running. This is db.js file.
const mysql = require('mysql');
let db_connected =false;
const ut_mysql_con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'pass',
database: "db"
});
mysql_con.connect(function(err) {
if (err) throw err;
else {
console.log("Connected!");
db_connected = true;
}
});
module.exports = mysql_con;
module.exports.db_connected = db_connected;
I also have an ejs file for front end from which ajax call is made.
<script>
$(document).ready(()=>{
//this where actual call would go if i knew how to do it.
});
</script>
I am comfortable with writing actually queries, but can't find a way of properly using ajax.
Thanks in advance for any guidance.

Woking with node.js and mysql

// So I am using mysql with node and express framework and the first time I created a test example everything worked fine. But then I tried to create a second project and now the routing seems to not being read.
And the respond back I get is:
[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
Server started on port 8000
mysql connected...
//I am also supposed to get the result back:
OkPackege{...
...
...
...
}
//But I am not getting it. Any Ideas...? thanks.
The scrips that i have are as follow:
const express = require('express');
const mysql = require('mysql');
const db = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'LEoking1987'
//database : 'nodesql'
});
db.connect((err) => {
if(err){
throw err;
}
console.log('mysql connected...');
});
const app = express();
// Creates satabase if it does not exist yet.
app.get('/createdb',(req,res) => {
let sql = 'CREATE DATABASE nodesql';
db.query(sql, (err, result) => {
if(err) throw err;
console.log(result);
res.send('Database created...');
});
});
app.listen('8000',()=>{
console.log('Server started on port 8000');
});
add debug: true in your mysql connection params like
mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'LEoking1987'
database: 'nodesql'
debug: true,
})