NodeJS and MySQL: Data not being stored in a variable - javascript

I am trying to extract data from the following MySQL query and storing it in a variable so I can use it but when I console log it to see if data was successfully pulled, I see a bunch of irrelevant stuff and not the data. Any help will be greatly appreciated it.
const body = req.body
const varQuery = await pool.query('SELECT id, name, email FROM registration WHERE email = ?', [body.email])
console.log(varQuery)

If you are using mysql, you have to pass callback as an argument, instead of using the async/await syntax. It would look something like that:
pool.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});```

Related

mysql2 node two consecutive database queries where the second query depends on the result of the first query

first of all: I am new to Node and also pretty new to JS. And asynchronous behavior seems to be something my brain refuses to understand.
I have the following issue:
I have a database table containing amongst other information the field "re_nummer" which stands for invoice number.
Each time my app creates an invoice, I want to read the actual re_nummer from the database, increase it by +1 and then write it back to the data base.
I assume this is a asynchronous behaviour and I have no spent a full day with google and here to solve the issue, but it seems the brain fog is too thick.
Here is my code:
const mysql2 = require("mysql2");
const db = mysql2.createConnection({
host: "localhost",
user: "root",
database: "mit_absicht_gluecklich",
});
db.connect((err) => {
if (err) throw err;
});
/**
* First database query: get the most recent invoice number (re_nummer)
*/
let sql = "SELECT re_nummer From admin WHERE id = 1;";
let re_nummer;
db.query(sql, (err, result) => {
if (err) throw err;
let re_nummer = result[0].re_nummer;
console.log("Rechungsnummer: ", re_nummer);
});
/**
* Second databas query: update database with re_nummer_neu = re_nummer +1
*/
let re_nummer_neu = re_nummer + 1;
sql = `UPDATE admin SET re_nummer = ${re_nummer_neu} WHERE id = 1;`;
db.query(sql, (err, result) => {
if (err) throw err;
console.log(re_nummer_neu);
});
module.exports = re_nummer;
This code doesn't work because it starts with the second database request before the first one i finalized.
How to solve this issue??
Also important to mention: this is a node module. I need the re_nummer to be available outside the module. This is why I use module.exports = re_nummer;
In case I am asking a question that has been asked already multiple times, I apologize in advance. I have honestly given my best to understand other threats with similar content. 100% fail!!!
Many thanks for some help and or comments!
Klaus

how to pass result from MySql query to ejs in node js

I am creating a dashboard that displays a number of data in different charts (e.g. horizontal bars, pie charts etc.)
I am using node js as a backend, MySQL as database, and ejs to render the data to html page.
I have had MySQL queries ready to query different data. The problem that I am having when I need to encapsulate these MySQL queries inside the routing function and pass the results to ejs.
Here is the sample code
router.get('/participant-module',(req,res)=>{
let sql1 = dbModel.participant_per_module; // MySQL query string
let sql2 = dbModel.error_per_module; // MySQL query string
let count_emp = [];
let count_error = [];
db.query(sql1, (err, result)=>{
if(err) throw err;
count_emp.push(result);
});
db.query(sql2, (err, result)=>{
if(err) throw err;
error_count.push(result);
});
res.render('dashboard', {emp_count:count_emp, error_count:count_error}); // pass array to ejs
});
count_emp and count_error are display in different charts. But, here the count_emp and count_error are always null.
I have tried to search for similar problem in the forum and the cause seems to be db.query is async so it won't wait and thus when res.render send the data, emp_count and error_count are still null.
So does anyone have a workaround on this?
Thank you in advance
D
Your db.query calls and res.render are running asynchronously without waiting for the query result. What is happening is that, your first query is fired, then immediately your second query is fired, then immediately your router is returning the response. You are not waiting for the queries to retrieve the results. That's why your count_emp and count_error is [] every time the response is rendered.
Try this:
router.get('/participant-module',(req,res)=>{
let sql1 = dbModel.participant_per_module; // MySQL query string
let sql2 = dbModel.error_per_module; // MySQL query string
let count_emp = [];
let count_error = [];
db.query(sql1, (err, result)=>{
if(err) throw err;
count_emp.push(result);
db.query(sql2, (err, result)=>{
if(err) throw err;
error_count.push(result);
res.render('dashboard', {emp_count:count_emp, error_count:count_error}); // pass array to ejs
});
});
});
PS: You should try to avoid over-nesting of callbacks. It is commonly referred as callback hell. Some common ways are: 1. Using promises 2. Using named functions

How do I get the information from the database before sending a message

I'm currently making a discord bot with discord.js v13. Right now I have a database where the guild.id and the standard prefix of a server are stored in. Now I want to rewrite a command which gets triggered by the prefix and the name of the command, like this '!somecommand'. Currently my prefix is defined in the file with a const variable, but I want the bot to check the database for the prefix the server has, and use this one instead. I'm checking the prefix in the database with this part of code:
pool.getConnection(function(err, connection) {
if (err) throw err;
let sql = `SELECT * FROM custom_prefix WHERE guild_id = '${message.guild.id}'`;
connection.query(sql, async function (err, result) {
if (err) throw err;
console.log(result[0].prefix)
connection.release();
});
});
The output is the current prefix of the server where the command was triggered, so far everything works fine.
But as I said I want the output of the code above to be the prefix with which the bot gets triggered.
I already tried to do it, but I'm always making a mistake.
Most of the time the bot is checking the database too slow and the result will be 'undefined'.
I dont know how I make the bot to wait for the result from the database, check if this result is really the prefix and then execute the command.
I am happy about any answer :-)
If you need any more information please let me know.
I'm guessing you did put the code that uses the result outside of the callback.
pool.getConnection(function(err, connection) {
if (err) throw err;
let sql = `SELECT * FROM custom_prefix WHERE guild_id = '${message.guild.id}'`;
connection.query(sql, async function (err, result) {
if (err) throw err;
console.log(result[0].prefix)
connection.release();
//
// Put your code that uses result[0].prefix here
//
});
});
//
// Do not put your code that uses result[0].prefix here
//

Trying to insert JSON into MySQL with Node.JS

using Node.JS I have a JSON output I've received from an API call. I'm trying to insert this JSON into MySQL but I keep getting the error message:
"Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ANU' at line 1"
Why is it rejecting the input request and how can I rectify this?
Additionally, I'd rather include multiple fields such as CountryName and CityName - how could I do this?
When analysing the JSON file in node.JS
console.log(typeof JSON) returns the output [object Object]
I think this is causing the error above as it is not in the correct format.
Node.JS extract:
//MySQL
let con = mysql.createConnection(config);
con.connect(function(err) {
if (err) throw err;
console.log("Connected to MySQL!");
var sql = "INSERT INTO TEST1 (CountryName) VALUES ?";
var values = obj.LocationsResponse.Country[1].CountryName;
con.query(sql, values, function (err, result) {
if (err) throw err;
console.log("Number of records inserted: " + result.affectedRows);
});
});
JSON extract (I have cleansed to keep it short):
obj = {"LocationsResponse":
{"Country":[
{"CountryName":"United Arab Emirates","CountryCode":"AE","City":[{"CityName":"Abu Dhabi","CityCode":"AUH"},{"CityName":"Dubai","CityCode":"DXB"}]}
,
{"CountryName":"Antigua","CountryCode":"AG","City":{"CityName":"Antigua","CityCode":"ANU"}}
,
{"CountryName":"USA","CountryCode":"US","City":
[{"CityName":"Albuquerque","CityCode":"ABQ",{"CityName":"Albany","CityCode":"ALB",{"CityName":"Amarillo","CityCode":"AMA",
{"CityName":"Anchorage","CityCode":"ANC"
}}}}]}
]}}
JSON has nothing to do with this error.
You just got the syntax for INSERT wrong.
You have:
INSERT INTO TEST1 (CountryName) VALUES ?
You should have:
INSERT INTO TEST1 (CountryName) VALUES (?)
MySQL also supports an alternative syntax:
INSERT INTO TEST1 SET CountryName = ?
Read https://dev.mysql.com/doc/en/insert.html for more on MySQL's INSERT syntax.

Find if a string is in a json file, then get the stuff around it

So I don't know a lot about JSON, I'm making a bot for a game that you can message and it sends you a code that you then send to my discord bot to link your account. I'm doing this by making it so whenever the bot is friended in game it accepts the request and sends a message to the user with a 5 Character code that is randomly generated and then stored in users.json with their player ID and Displayname. I'm done with the bot part mostly just the discord part now, I need to find if the code they input is in the json file and then get the displayName that goes with that code. If that makes sense...
Here's users.json with only one entry:
{"users":[{"name":"ImBattleDash","Id":"34a02cf8f4414e29b15921876da36f9a","code":"5MJS3"}]}
and here's the code to add to it:
fs.readFile('./users.json', 'utf-8', function(err, data) {
if (err) throw err
var arrayOfObjects = JSON.parse(data)
arrayOfObjects.users.push({
name: userAuthorName,
Id: userAuthor,
code: authorCode
})
console.log(arrayOfObjects)
fs.writeFile('./users.json', JSON.stringify(arrayOfObjects), 'utf-8', function(err) {
if (err) throw err
console.log('Done!')
})
What I basically need is to search in the Json file for example if one of the codes is "5MZJ2" and if it is then get the name that goes with that and set it to a variable.
I've been trying to figure out how to do it but I'm still quite a beginner so some help would be appreciated!
A quick way to do it is to use the find() method, a solution would be:
let myCode = "5MJS3"
fs.readFile('./users.json', 'utf-8', function (err, data) {
if (err) throw err
var arrayOfObjects = JSON.parse(data)
let myEntry = arrayOfObjects.users.find(entry => entry.code == myCode)
console.log(myEntry.name)
})
It basically go through your list and looks for an entry mathing the code :)

Categories

Resources