Node MYSQL exports returns undefined - javascript

I am creating a discord bot that has integration with mysql. To make it easier, I created a central file for the mysql database (configs/mysql.js) and, when the command needs it, it will send the query request to that file and finally, it will return the processed value. But when I try to do this, the return is undefined in the console (of the command), but in the mysql.js console, it shows the correct value.
MYSQL.js Code
const mysql = require("mysql");
const connection = mysql.createConnection({
host: config.URL,
user: config.dbUser,
password: config.dbPassword,
database: config.database
});
connection.connect(function(err) {
if (err) {
console.error("[MYSQL] Error on Connection: " + err.stack);
return;
}
console.log("[MYSQL] Connected with ID " + connection.threadId + "!");
});
function query(sql) {
connection.query(sql, function(error, result, fields) {
if (error) return error;
const analise = JSON.stringify(result[0]);
console.log(analise) //it's return the value correct
return analise
});
}
exports.connection = connection;
exports.query = query;
The Request
const status1 = await mysql.query("SELECT `status` FROM `server_status`");
console.log(status1); //it's return undefined
Can anyone help me?

Use promise for mysql you can`t use return in callback function.
const mysql = require('mysql');
const connection = mysql.createConnection({
host: config.URL,
user: config.dbUser,
password: config.dbPassword,
database: config.database,
});
connection.connect(function(err) {
if (err) {
console.error('[MYSQL] Error on Connection: ' + err.stack);
return;
}
console.log('[MYSQL] Connected with ID ' + connection.threadId + '!');
});
function query(sql) {
return new Promise(resolve => {
connection.query(sql, function(error, result, fields) {
if (error) return error;
const analise = JSON.stringify(result[0]);
console.log(analise); //it's return the value correct
resolve(analise);
});
});
}
exports.connection = connection;
exports.query = query;
const status1 = await mysql.query("SELECT `status` FROM `server_status`");

Related

Querying Amazon Redshift using node.js Lambda function returns null

When I try this code in local its works fine but not in an AWS Lambda function.
var Redshift = require('node-redshift');
var client = {
user: 'root',
database: 'yourdatabasename',
password: 'yourpassword',
port: 5439,
host: 'localhost',
};
var redshiftClient = new Redshift(client, {rawConnection:true});
exports.handler = async (event) => {
let response = [];
redshiftClient.connect(function(err){
console.log('After Connection');
if(err) throw err;
else{
redshiftClient.query('SELECT * FROM world.country', {raw: true}, function(err, data){
if(err) throw err;
else{
response = data;
console.log(data);
redshiftClient.close();
}
});
}
});
return response;
};
Could anyone tell me what's the matter with my coding?
Thank you very much!

How to correctly write module in Node.JS?

So I'm trying to make it so I don't have to have multiple connections to my database when I can just put my connection and runQuery function in a file and just require it in another file. Here is what I have in my "mysql.js" file.
const mysql = require('mysql');
module.exports = function () {
let connection = mysql.createConnection({
host: '------',
user: 'voltclou_site',
password: '----',
database: process.env.database
})
connection.connect(function(err) {
if (err) {
console.error('[DATABASE] Error connecting: ' + err.stack);
return;
}
console.log('[DATABASE] Connected as id ' + connection.threadId);
});
async function runQuery(query, values) {
return new Promise((resolve, reject) => {
connection.query(query, values, function (error, results) {
if (error) return reject(error)
return resolve(results)
})
})
}
}
Here is how I would like to require it in my files:
const { connection, runQuery } = require('./functions/mysql')
Am I doing this correctly? I'm new to this whole module thing. I've been trying to split my files up because one index.js with 3000+ lines is insane. Thanks for any help.
No you didnt do it correclty. What you have done you have exported it as an default but you want to export named functions. You can do it like:
const mysql = require("mysql");
let connection = mysql.createConnection({
host: "81.19.215.6",
user: "voltclou_site",
password: "yogO{6,F#8WS",
database: process.env.database
});
connection.connect(function(err) {
if (err) {
console.error("[DATABASE] Error connecting: " + err.stack);
return;
}
console.log("[DATABASE] Connected as id " + connection.threadId);
});
async function runQuery(query, values) {
return new Promise((resolve, reject) => {
connection.query(query, values, function(error, results) {
if (error) return reject(error);
return resolve(results);
});
});
}
module.exports = {
connection,
runQuery
};
The value you've described, { connection, runQuery }, should be the value assigned to module.exports:
const mysql = require('mysql');
let connection = mysql.createConnection({ ... });
connection.connect(...);
let runQuery = async (query, values) => { ... };
module.exports = { connection, runQuery };
You may not even need to export connection, if all you need elsewhere is runQuery!

Node.js module export "pre-load"

This is in a mysql.js file:
const mysql = require('mysql');
const config = require('./config.json');
const con = mysql.createConnection({
host: config.dbhost,
user: config.dbuser,
password: config.dbpass,
database: config.dbname,
});
module.exports = {
findUser: function(email) {
const sql = 'SELECT * FROM users WHERE email = ' + mysql.escape(email);
con.connect(function(err) {
if (err) throw err;
console.log('Connected!');
con.query(sql, function(err, result) {
if (err) throw err;
return result[0].id;
});
});
},
};
then within my index.js file there is this:
const mysql = require('./mysql.js');
console.log(mysql.findUser('example#example.test'));
When the code is running, it outputs "undefined" and then "Connected!" after the db connection is made. Even though if I do a console.log on result[0].id it outputs 1, which is the correct id...
Question: How can I load the mysql.js file first before the function is called?
You need to wait for response cause its an asynchronous function.
Try using callback or promises.
Callback example:
mysql.findUser('example#example.test', function(res)){ console.log(res)});
module.exports = {
findUser: function(email, callback) {
const sql = 'SELECT * FROM users WHERE email = ' + mysql.escape(email);
con.connect(function(err) {
if (err) throw err;
console.log('Connected!');
con.query(sql, function(err, result) {
if (err) throw err;
callback(result[0].id);
});
});
},

How to get result from function in other file in node.js

Trying to call database query from other javascript file in NodeJS.
Sample database file:
function addUser(user) {
connection.connect(function (err) {
if (err) {
console.error('Error connecting: ' + err);
}
console.log('Connected as id ' + connection.threadId);
});
var sql = "INSERT INTO `mobile`.`main` (`userId`) VALUES (?);"
var inserts = [user];
connection.query(sql, inserts, function (error, results) {
console.log('query');
if (error) {
return error;
} else {
console.log('Success Query');
return results;
}
});
connection.end(function (err) {
if (err) {
console.error('Error connecting: ' + err);
}
console.log('Connection closed!');
});
}
module.exports = addUser;
Sample main.js file:
app.get('/api/mysql/:user', function (req, res) {
var user = req.params.user;
addUsers(user)
res.json({
SQLResp: 'Query succes',
result: addUsers.result
});
});
How to get the result from the first file and use it as a response in the main js?
Welcome to stack overflow.
this is missing from your database file, How did you got connection there?
Here's a sample example over How to export database connection and use this to make calls from other files.
Also do read about callbacks-functions, Promises, async-await and Asynchronous functions of JavaScript. These are basics of JavaScript and also do go through NodeJS docs.
DB.js:
const MYSQL = require('mysql');
const connection = MYSQL.createConnection({
host: 'localhost', // url of db
user: 'root',
password: 'root',
database: 'dbName'
});
module.exports = connection;
Now will use this connection from other file to call database.
app.js:
const db = require('./DB'); // Path of your db connection file. I named it DB.js on same level as of app.js
function addUser(user) {
// Since database calls are async in NodeJS thus using promises.
return new Promise ( (resolve, reject) => {
db.connect(function (err) {
if (err) {
console.error('Error connecting: ' + err);
return reject(err);
}
console.log('Connected as id ' + connection.threadId);
});
var sql = "INSERT INTO `mobile`.`main` (`userId`) VALUES (?);"
var inserts = [user];
db.query(sql, inserts, function (error, results) {
console.log('query');
if (error) {
return reject(err);
} else {
console.log('Success Query');
return resolve(results);
}
});
db.end(function (err) {
if (err) {
console.error('Error connecting: ' + err);
}
console.log('Connection closed!');
});
});
}
app.get('/api/mysql/:user', function (req, res) {
var user = req.params.user;
addUsers(user)
.then (result => { // When addUsers will resolve promise will be in then.
res.json({
SQLResp: 'Query succes',
result: result
});
})
.catch(err => { // If promise is rejected then on catch
res.json({
SQLResp: 'Query err',
result: err
});
});
});
You need to pass a callback into your addUser function, and call it inside your connection.query with the results.
Currently, when you return, you're returning inside another callback, which means the data is more or less being thrown away.
That will also let you handle all of the error cases in a way you can tell the user about.

does not work module.exports

file ConnectToDB
var pg = require("pg");
var dataWithDB = require('./DataBase/ConnectToDb');
var pool = new pg.Pool({
host: "localhost",
port: "5432",
user: "postgres",
password: "111111",
database: "hrs"
});
pool.connect(function (err,client,done) {
if(err)console.log("connect " + err.toString());
else
client.query('SELECT id, "idName", "idContact", "idExperience",
"idSkill", "dateAdded", "dateColloquy"' +
'FROM public."applicant ";',function (err,result) {
if(err) {
//console.log("query " + err.toString());
exports.res = "Data NOT";
}
else {
console.log(result.rows);
module.exports.resul = result.rows;
}
done();
});
});
pool.end()
file app.js
var dataWithDB = require('./DataBase/ConnectToDb');
console.log(dataWithDB + " wit DB");
as a result deduces to me undefined wit DB
but should data from db
Can an error in the scope?
Data is sent if you specify at the end of the file module.exporst.result = "Example".
You should encapsulate your connect to db code in a function which takes a callback.
Here is an example, hopefully you get the idea. :)
./DataBase/ConnectToDb
var pg = require("pg");
module.exports = (callback) => {
var pool = new pg.Pool({
host: "localhost",
port: "5432",
user: "postgres",
password: "111111",
database: "hrs"
});
pool.connect(function (err, client, done) {
if (err) {
console.log("connect " + err.toString());
} else {
let query = 'SELECT id, "idName", "idContact",' +
' "idExperience","idSkill", "dateAdded", "dateColloquy"' +
'FROM public."applicant ";'
client.query(query, function (err, result) {
if (err) {
//console.log("query " + err.toString());
exports.res = "Data NOT";
callback(err);
}
else {
console.log(result.rows);
callback(null, result);
}
done(); // Not sure what this does! :-o
});
}
});
// Is this trying to close it before we've connected?
// It should probably be up above...
pool.end()
}
app
var connectToDb = require('./DataBase/ConnectToDb');
connectToDb((err, result) => {
// This is a callback!
if(err) console.log(err)
else console.log(result)
})
Do a google search for: node.js callback pattern
Here is what you should do: import a different callback function that you pass into your query. This callback will do whatever you want with result. As written, your method will not work and does not make sense.

Categories

Resources