Can't access all values of array - javascript

I am getting a row from mysql into an array using node-mariasql.
When I print this array out using my Winston logger, I get this:
steamid=76561198053558238, tradePartnerId=93292510, tradeToken=T3dZTnlq, autoSendWinnings=1, profilePrivacy=0, earnings=0.00, lastKnownName=jdK jdK, avatar=https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/49/4955f3be7e9b9d16e8fc0b16ed2407ba9b4c563c.jpg, avatarLarge=https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/49/4955f3be7e9b9d16e8fc0b16ed2407ba9b4c563c_full.jpg
If I print out the value for "steamid", I get this as a return:
76561198053558238
However, if I print out the value for "autoSendWinnnings" or "profilePrivacy", I get "undefined" as a return.
Why is that? What am I doing wrong? I don't think it is a MySQL related issue, because if I print out the whole array, I obviously get all values.
Still, I'll append the relevant code here.
statements['get_user'] = sql.prepare('SELECT * FROM `users` WHERE steamid=:steamid');
function getUser(steamid, callback) {
sql.query(statements.get_user({ steamid: steamid }), { useArray: true }, function(err, rows) {
if(err)
logger.error('A MySQL error occured: ' + err);
callback(rows);
});
}
getUser('76561198053558238' function(user) {
logger.debug(user); // I get the whole array here
logger.debug(user.steamid); // I get the value for steamid here
logger.debug(user.autoSendWinnings); // I get undefined here
});
Thanks in advance,
I hope someone can help me.

Your callback receives an Array of result rows. For reasons unknown said Array has a property steamid.
Try
getUser('76561198053558238', function(users) {
logger.debug(users);
logger.debug(users[0].steamid);
logger.debug(users[0].autoSendWinnings);
});

Related

Fetch a field from a Multiple MySQL Query in NodeJS?

I'm using NodeJS and need to fetch an audioid field from my first MySQL query, assign it to a variable and use that variable in my next MySQL query. So I've tried to use;
var newaudioid = results[0].audioid;
But the result is coming back as "undefined".
Here's the code;
connection.query(sql, [1, 2], function(err, results, fields){
if (!err) {
res.send(JSON.stringify(results[0]) + JSON.stringify(results[1]));
console.log(results[0]);
console.log(results[1]);
var newaudioid = results[0].audioid;
console.log('newaudioid = ' + newaudioid);
} else {
console.log('Error while performing query.');
console.log(err);
}
});
So console.log('newaudioid = ' + newaudioid); gives me back newaudioid = undefined
How can I fetch that audioid field from my first query?
Following up on your comment
SO I stringified IE: console.log('results0 = ' +
JSON.stringify(results[0])); and got results0 =
[{"audioid":144},{"audioid":147}]
Inside results[0] you have 2 objects that themselves have another object inside, and they both have the same property name. The problem is that javascript does not know which one you are referring to when you are saying results[0].audioid
What you can do is use [0] again to get the first one again, so that would be: results[0][0]

NodeJS MySQL Returning Empty Array When Passing Integers To Query

SECOND EDIT
The issue was caused by the MAX_INTEGER_VALUE which is lower then the integer value I was passing. I changed the MySQL table column to TEXT instead of BIGINT and everything is being returned correctly.
Thanks for all the help!
EDIT
So I just realized that the userID variable and the guildID variables are being passed using this line of code.
mysqlModule.userCrewSearch(575783451018526744, 282997056438665217);
However the values that are being supplied to the SQL statement turn the last two digits of the number into '00'. So instead of 575783451018526744 the value being passed into the SQL statement is 575783451018526700.
So why is this value being changed when nothing I am doing in my code is changing these values?
Original Post
I'll keep this short and sweet. I'm trying to run a query using the nodejs MySQL package. I'm not sure where I'm going wrong but whenever I call my function that executes my query, I'm always returned an empty array, unless I hardcode the values into the SQL query.
Heres the code:
// Search for the User's Crew
function userCrewSearch(guildID, userID) {
pool.getConnection(function(err, connection) {
if(err) {
return console.log(err);
}
var sql = "SELECT * FROM `crew-members` WHERE `userID`=? AND `guildID`=?;";
console.log(sql);
connection.query(sql, [guildID, userID], function(err, results) {
connection.release(); // always put connection back in pool after last query
if(err) {
return console.log(err);
}
return console.log(results);
});
});
}
I'm calling this function like so: userCrewSearch(575783451018526744, 282997056438665217);
Both of the values I'm passing are integers. However this is what I get in my console.
However, here is my code with the values hardcoded into the SQL... to which the code then returns the result in the form of a RowDataPacket.
// Search for the User's Crew
function userCrewSearch(guildID, userID) {
pool.getConnection(function(err, connection) {
if(err) {
return console.log(err);
}
var sql = "SELECT * FROM `crew-members` WHERE `userID`=282997056438665217 AND `guildID`=575783451018526744;";
console.log(sql);
connection.query(sql, [guildID, userID], function(err, results) {
connection.release(); // always put connection back in pool after last query
if(err) {
return console.log(err);
}
return console.log(results);
});
});
}
Heres the result.
Bonus Question: How do I handle the RowDataPacket? Can I convert this directly into an object so I can call results.crewID and return just that value?
Same problem i was facing few days ago. I have solved this by converting the parameters into string.
function userCrewSearch(String(guildID), String(userID)) {
// your code here
}
Try adding + before your numeric parameter, it converts into number, it worked for me-
connection.query(sql, [+guildID, +userID], function(err, results) {
for your bonus questions answer, you can directly access the crewID or some other key using,
results[0].crewID
or do something like -
const [ result ] = results;
console.log(result.crewID)

Querying MySQL with JS Object returning [object Object] as table name

I'm building a program that queries MySQL databases, gets the tables, fields, field data types, and entries and returns it as a single object to be later used to view the MySQL data as a table.
This is what the built object will look like:
{
`Table_Name`: {
Title: `Table_Name`,
Fields: {
`Field Name`: `Datatype`
},
RowData: []
}
}
The query to get the tables is fine, however the query to get the row data isn't. The query function looks like this:
function getRows(){
let secondpromises = [];
secondpromises.push(
new Promise((resolve, reject) => {
for(x in Tables){
Connect_SQL(SQLcreds, w_newSconn, (conn) => {
conn.query(`SELECT * FROM ${Tables[x]}`, (err, results) => {
if(err){
console.log(err);
reject(err);
}else{
for(r in results){
Tables[`${Tables[x].Title}`].RowData.push(results[r]);
}
resolve(results);
}
});
});
if(x == Tables.length - 1){
Promise.all(secondpromises).then(() => {
if(w_newSconn){
w_newSconn.close();
w_newSconn = null;
}
console.log(Tables);
});
}
}
})
);
}
The error is coming from conn.query(). It is throwing an error stating there is an error in my SQL syntax at:
SELECT * FROM [object Object]
I understand the reason why and I'm sure there is a way to resolve this through JSON.Stringify() but there must be a simpler way. I have already tried creating a variable like so:
let objArray = Object.keys(Tables)
But it still returned [object Object], any help would be appreciated.
Tables[x] is an object. You need to get the table name from it.
conn.query(`SELECT * FROM ${Tables[x].Title}`, (err, results) => {
It also looks like the property name is the same as the title, so you can do:
conn.query(`SELECT * FROM ${x}`, (err, results) => {
I ended up creating a variable in the loop
let table = keys[x]
and that did the trick, for whatever reason ${keys[x]} was returning undefined but the variable returned the table name. Theoretically I could have changed the for loops to a
for(x in Tables)
and x would have returned the title so I may go back and rewrite it that way. Thank you.

Cannot retrieve key values with Parse.Query

Beginner programmer here...I am trying to retrieve the value of specific key from a Parse object. I know that I am retrieving the object because certain keys return a value, i.e. createdAt returns the date value associated with it....the key I want the value for is called "task", which has a string value, but keeps returning undefined. My code looks like this:
var query = new Parse.Query("TestObject");
query.get("TC8m9X6XUB", {
success: function(object) {
console.log(object.task);
},
error: function(error) {
console.log("An error occured :(");
}
});
if I replace "object.task" with "object.createdAt" it returns a value. What am I missing here?
createdAt, objectId are reserver for Parse. So you can directly call them like object.createdAt. However, if you have a column namely task which has string value then you have to get the value via calling object.get("task"). Hope this helps.
Regards.
Use get().
In your case,
object.get('task');
Test this,
var query = new Parse.Query("TestObject");
query.get("TC8m9X6XUB", {
success: function(object) {
console.log(object.get('task'));
},
error: function(error) {
console.log("An error occured!");
}
});
In Parse, createdAt, ID and updatedAt are special fields. Hence, you can retrieve them without get().

Getting an object from MongoDB using its id

Let me explain my problem first.
I am trying to get the ID from URL and use it to find a record in the database(MongoDB). The following code I have in NodeJS Express App.
app.post('/dashboard/profile/update/:id',function(req,res){
var to_update=req.params.id;
var firstName=req.body.fname;
obj_to_search={_id:to_update};
db.open(function(err, dbs) {
if(!err) {
dbs.collection('project',function(err, collection) {
//update
collection.findOne(obj_to_search, function(err, result) {
if (err) {
throw err;
} else {
res.send(result);
}
dbs.close();
});
});
}
});
});
I am getting the record if I hard code the ID to 1. But I am not getting the record by this way. However I have checked using console.log the ID i am getting through URL is also 1.
Convert strings to integers
If a variable is in the url - it's a string. If you're wanting to query the database with a number, you'll need to cast it to a number for use in the query:
obj_to_search={_id: parseInt(to_update,10)};

Categories