Can't parse JSON returned from MySQL - mysql

I have a Node.js app that is writing data to a MySQL backend. One field is an array I stringify. I can see in the workbench the data is correct when in the database. However when I retrieve it I am getting an error when I try to parse it.
"Unexpected token o in JSON at position 1"
If I log the result it shows up as [Object Object].
From what I read online this means it is already a JS object and I do not need to parse it. However I cannot find anything about how to get access to the data.
process: function (bot, msg, suffix) {
var ftcmds = suffix.split(" ", 1);
var ftName = ftcmds[0];
var ftArray;
var selectSQL = "SELECT FireTeam FROM fireteam WHERE Name = '" + ftName + "'";
var updateSQL = "UPDATE fireteam SET FireTeam = '" + ftArray + "'WHERE Name = '" + ftName + "'";
mysqlcon.query(selectSQL, function (err, result) {
console.log("Result |" + result);
console.log("Error |" + err);
if (err) {
console.log("Caught Error " + err + " " + msg.author);
}
else {
console.log("Recovered result " + result);
ftArray = result;
console.log("Attempting to update array");
ftArray.push(msg.author.id);
console.log("updated array " + ftArray);
var jsonArray = JSON.stringify(ftArray);
mysqlcon.query(updateSQL, function (err, result) {
console.log("Result |" + result);
console.log("Error |" + err);
if (err.toString().indexOf(dupErr) != -1) {
msg.author.send("Could not find that fireteam");
console.log("Error: Did not locate the requested name " + msg.author)
} else if (err) {
console.log("Caught Error " + err + " " + msg.author);
}
else {
msg.author.send("You have joined Fireteam " + name + ". I will setup a group chat on " + date + " if your team fills up.");
}
})
}
});
}

You should just be able to access it as an object, so if result has fields name and title you can just access them as:
var name = result.name
var title = result.title

Related

NodeJS MySQL Query results to [object Object]

I have this code:
var sql1 = "SELECT DISTINCT sensor_id, timestamp FROM Displacement_Record WHERE wave_type = 1 ORDER BY timestamp ASC";
var sql2 = "SELECT timestamp FROM Displacement_Record WHERE wave_type = 0 AND sensor_id = ?";
var sql3 = "SELECT latitude, longitude FROM Sensor_Record WHERE sensor_id = ?";
var pTime, sTime;
db.getConnection((err, conn) => {
if (err) throw err;
conn.query(sql1, function (err, res, fields) {
if (err) throw err;
for (i = 0; i < res.length; i++) {
var sensor = res[i].sensor_id;
console.log(sensor);
var pTime = res[i].timestamp;
sql2 = mysql.format(sql2, sensor);
conn.query(sql2, function (err, results, fields) {
if (err) throw err;
var sTime = res[i].timestamp; //timestamp error
console.log("results = " + results + " " + results.length);
conn.query(sql3, function (err, res, fields) {
if (err) throw err;
var location = [res[i].latitude, res[i].longitude];
console.log("Data = " + sensor + " " + pTime + " " + sTime + " " + latitude + " " + longitude);
});
});
}
});
conn.release();
});
The first query give me the results properly. I am able to get and store the data I need. However, the second and third query results as:
results = [object Object],[object Object],[object Object]
and throws:
throw err; // Rethrow non-MySQL errors
^
TypeError: Cannot read property 'timestamp' of undefined
I tried to see what causes this. I am able to get a proper result only when I remove the condition in the query. However, I need the condition of course. And I'm also wondering how come it throws error in the following queries when I am able to get results on the first query, with conditions and all.
I hope somebody can help me, thanks!
The problem is actually not really a problem. when you have [object Object] in any console.log, it means that what you want to print in a string is not possible to print as a string.
If you really want to print the result, what you should do instead of
conn.query(sql2, function (err, results, fields) {
if (err) throw err;
console.log("results = " + results + " " + results.length); // HERE
conn.query(sql3, function (err, res, fields) {
if (err) throw err;
var location = [res[i].latitude, res[i].longitude];
console.log("Data = " + sensor + " " + pTime + " " + sTime + " " + latitude + " " + longitude); // HERE
});
});
Is actually :
conn.query(sql2, function (err, results, fields) {
if (err) throw err;
console.log("results ="); // HERE
console.log({ results }, results.length); // HERE
conn.query(sql3, function (err, res, fields) {
if (err) throw err;
var location = [res[i].latitude, res[i].longitude];
console.log("Data = "); // HERE
console.log({ sensor, pTime, sTime, latitude, longitude }); // HERE
});
});
See the notation console.log({ variable });
This allows you to log your variable content, with the key displayed on the left, as you'd actually want to do in your current console.logs.
Example :
const results = [1, 2, 3, 4];
const randomString = 'Some content in here';
console.log({ results, randomString});
This outputs :
You can't console combination of string and object at once time.
Try below format, It might help you.
console.log('results =');
console.log(results);
console.log(results.length);

NodeJS and MYSQL Issue

My code is supposed to retrieve the "DropsRemaining" for a user ID (which it does successfully) and then -1 from the number it retrieves. When retreiving the data it returns this string "[ RowDataPacket { DropsRemaining: 5 } }" however the end of the code does not -1 from the DropsRemaining it instead sets the DropsRemaining to -1. If anyone can help fix this I'd really appreciate it.
var sql = "SELECT DropsRemaining FROM UserData WHERE DiscordID LIKE " + message.author.id;
var DropCount = [];
connection.query(sql, function (err, result) {
if (!err)
setValue(result);
else
console.log("No Information For That User Found");
});
function setValue(value) {
DropCount = value;
console.log(DropCount);
};
//Remove drop from user
DropCount = DropCount - 1;
var sql = "UPDATE UserData SET DropsRemaining = " + DropCount + " WHERE DiscordID = " + message.author.id;
The problem is that the order you write your Javascript code is not exactly how it is performed in the end.
When you call the connection.query() function, the next line of code does not necessarily already have the result of that function.
I would recommend you to have a look on this book series, they have really good explanations about those characteristics.
Probably the following code will output the expected response. Notice that I nested the code, therefore I can control the flow properly.
var sql = "SELECT DropsRemaining FROM UserData WHERE DiscordID LIKE " + message.author.id;
// Get the DropsRemaining
connection.query(sql, function (err, result) {
if (!err) {
// No errors in the query, decrement the Drops
decrementDrop(result);
} else {
console.log("No Information For That User Found");
}
});
function decrementDrop(dropsAvailable) {
var dropsRemaining = dropsAvailable - 1;
var updateSql = "UPDATE UserData SET DropsRemaining = " + dropsRemaining + " WHERE DiscordID = " + message.author.id;
// Update the DropsRemaining column to the dropsRemaining, i.e., decrement the DropsRemaining column value
connection.query(updateSql, function (err, result) {
if (!err) {
console.log("DiscordID = " + message.author.id +" has " + dropsRemaining + " drops remaining")
} else {
console.log("Error!");
}
});
}

Loop through MySQL rows and store results in array

I am trying to store details of affectedRows from a MySQL INSERT query using NodeJS. My mind is melting trying to comprehend callbacks and Promises. Being a single-man dev team I wanted to reach out and ask for the clearest explanation as to how a callback can be applied here in a foreach loop.
The goal should be clear from these few lines of code; store data in the affected_rows[] array.
var affected_rows = [];
asset_array.forEach(function(asset) { // Populate the asset table
var query_string = "INSERT IGNORE INTO " + asset_table + " SET symbol = '" + asset[0] + "', name = '" + asset[1] + "'";
connection.query(query_string, function(err, rows, fields) {
if (err) throw err;
if ( rows.affectedRows > 0 ) {
data_to_push = [asset_table, asset[0], asset[1]];
affected_rows.push(data_to_push);
}
});
});
console.log(affected_rows); // [] for obvious async reasons
One option would be to process the asset_array inside a function and pass a callback into it and when loops through asset_array check if the current index matches the asset_array length (-1). If so call the callback.
var affected_rows = [];
function processAssets(cb) {
var array_len = asset_array_len.length
asset_array.forEach(function(asset, index) {
var query_string = 'INSERT IGNORE INTO ' + asset_table + ' SET symbol = \'' + asset[0] + '\', name = \'' + asset[1] + '\'';
connection.query(query_string, function(err, rows, fields) {
if (err) throw err
if (rows.affectedRows > 0) {
data_to_push = [asset_table, asset[0], asset[1]];
affected_rows.push(data_to_push);
}
if (index === (array_len - 1)) cb()
});
});
}
processAssets(function() {
console.log(affected_rows)
})
Will suggest you to have a look at async Queue.
You can change your code like this to use it.
//2nd Step - Perform each task and then call callback() to move to next task
var q = async.queue(function(query_string, callback) {
connection.query(query_string, function(err, rows, fields) {
if (err) throw err;
if ( rows.affectedRows > 0 ) {
data_to_push = [asset_table, asset[0], asset[1]];
affected_rows.push(data_to_push);
}
callback(); //call next task
});
}, 2); //here 2 means concurrency ie 2 tasks will run in parallel
//Final Step - Drain gives you end of queue which means all tasks have finished processing
q.drain = function() {
//Do whatever you want after all tasks are finished
};
//1st Step - create a queue of all tasks that you need to perform
for (var i = 0; i < asset_array.length ; i++) {
var query_string = "INSERT IGNORE INTO " + asset_table + " SET symbol = '" + asset[0] + "', name = '" + asset[1] + "'";
q.push(query_string);
}

Nested mysql query in each loop

So all i want to do is to make a query to get all id's from the database and then i want to do my method for the id and update the row in the database.
So i created this code. But all it is doing is to get the ids and do not the nested query with the insertString1.
var mysql = require('mysql');
var _ = require("underscore");
var connection = mysql.createConnection({
host : 'myHost.net',
user : 'myUser',
password : 'myPassword',
database : 'myDatabase'
});
connection.query('SELECT * FROM `idmarkethash`', function (error, results) {
_.each(results, function (row) {
// here i want to calculate the new values of the row
// This insert query is just an example
var insertString1 = "UPDATE idmarkethash SET " +
"Price=" + mysql.escape(2.00) + ", " +
"Gradient=" + mysql.escape(2.00) + ", " +
"LastUpdated=" + mysql.escape("2015-08-31 00:00:11") + " " +
"WHERE Id=" + mysql.escape(181) + ";";
connection.query(insertString1, function (error1, result1) {
console.log(result1);
});
});
});
I tried the same with the async package:
var async = require('async');
// Packages are all included.
connection.query('SELECT * FROM `idmarkethash`', function (error, results) {
async.each(results, function (row, callback) {
// here i want to calculate the new values of the row
// This insert query is just an example
var insertString1 = "UPDATE idmarkethash SET " +
"Price=" + mysql.escape(2.00) + ", " +
"Gradient=" + mysql.escape(2.00) + ", " +
"LastUpdated=" + mysql.escape("2015-08-31 00:00:11") + " " +
"WHERE Id=" + mysql.escape(181) + ";";
connection.query(insertString1, function (error1, result1) {
console.log(result1);
callback();
});
});
});
With debugging i could see that the declaration of insertString1 is called, but the second query is not fired / or the loop continues without recognizing the second query.

Converting html to Json object

I'm currently working on a project where I need to convert some older code into a json object. We're taking the result set from a sql query and returning the categories it gives back as json. I'm not that well versed in javascript let alone json so I'm not sure what's the simplest way to go about this. Here is the function I need to change into JSON:
function createOutputCategories(){
try
{
output =
"<html>" +
"<head>" +
"<title>" +
"You can find it!" +
"</title>" +
"</head>" +
"<body bgcolor='#CED3F3'>" +
"<a href='" + url + "file.xsjs?parent=1'>" +
"</a>" +
"<br><br>";
if(parent === "1"){
output = output + "<h3><font color='#AAAAAA'>Home</font>";
}else{
output = output +"<a href='javascript:history.back()'>" +
"<h3>Back";
}
output = output +
"</h3>" +
"</a>" +
"<h1>" +
"Categories:" +
"</h1>";
while(rs.next()){
if(rs.getString(3) === 0 || rs.getString(3) === null || rs.getString(3) === undefined || rs.getString(3) === "0" ){
output = output + "<br><a href='" + url + "yeti.xsjs?parent=" + rs.getString(1) + "'>" + rs.getString(2) + "</a>";
}else{
output = output + "<br><a href='" + url + "yeti.xsjs?parent=" + rs.getString(1) + "'>" + rs.getString(3) + "</a>";
}
}
}catch(Exception){
$.response.contentType = "text/plain";
$.response.setBody( "Failed to retreive data" );
$.response.status = $.net.http.INTERNAL_SERVER_ERROR;
}
Here is what I have so far but I am not returning a valid JSON object:
function createOutputCategories(){
try{
output =
"category: {name = \"" + parent + "\"; description = \"\"}";
output = output +
"subcategories: [ ";
while(rs.next()){
output = output +
"{ catid = \"" + rs.getString(1) + "\"; catname = \"" + rs.getString(2) + "\"; altname = \"" + rs.getString(3) + "\"; description = \"" + rs.getString(4) + "\"}";
}
output = output +
"];";
}
catch(Exception){
$.response.contentType = "text/plain";
$.response.setBody( "Failed to retreive data" );
$.response.status = $.net.http.INTERNAL_SERVER_ERROR;
}
If I need to provide anything else please let me know! Thanks!
Do you want to output a javascript object to a string?
Construct the object:
var category=new Object();
category.name="Name";
category.description="My lovely description";
category.subcategories=[];
var subCat=new Object();
subCat.catid=1;
subCat.catname="My subcat";
category.subcategories.push(subCat);
Alternatively, you could construct the object using literals:
var category={
name:"Name",
description:"My lovely description",
subcategories:[
{catid:1,catname:"My subcat"}
]
};
Then return the object as string.
return JSON.stringify(category);
A reference to Javascript objects if you need more help:
http://www.w3schools.com/js/js_objects.asp