Fetch a field from a Multiple MySQL Query in NodeJS? - javascript

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]

Related

how to pass list of ids to mysql delete query from NodeJs

i need to do a multiple row delete query with the where clause in list (id1,id2..)
But since we don't have lists in JS i'm having a problem with passing the parameters to the query.This is my code:
let list =[1,2,..];
let Query = 'DELETE FROM Table WHERE id IN (?)';
connection.query(Query,list, function (err, result) {
`enter code here`
};
when i pass it this way and after logging the mysql server to a Logfile i see that it actually passes only the first id.
PS : i tried without the parentheses around ? and also doing a Array.join on the list but both didn't work.
Read in document of https://github.com/mysqljs/mysql#performing-queries (if you use this lib to connect mysql)
let list =[1,2,..];
let Query = 'DELETE FROM Table WHERE id IN (?)';
// values param need is a array of value to binding to "?"
// you can try [list.toString()] if the block above not working
connection.query(Query,[list], function (err, result) {
`enter code here`
};
Simply append the list of items to the query string:
let list = [1, 2, 3];
let Query = `DELETE FROM Table WHERE id IN (${list})`;
connection.query(Query, function (err, result) {
`enter code here`
};
Unfortunately, ? placeholders don't work with the IN operator. So you should escape the values. Say the list variable is coming from an external source; so to prevent SQL Injection you can:
// `list` is filled in outside this process
const Query = `DELETE FROM Table WHERE id IN (${list.map((item) => connection.escape(item))})`;
connection.query(Query, function (err, result) {
// handle error or result here
};
I noticed that list.map(connection.escape) won't work and throw:
TypeError: Cannot read property 'config' of undefined

Using value set inside mysql query from outside the query

I'm using the mysql module and am doing multiple queries into my Mysql database. I'm getting an error in my NodeJS code where the variable "updateQuery" is undefined, even though I set it inside the first query. I thought that since this is synchronous (one query getting executed after the previous finishes) that the variable would be set. I do not want to nest the 2nd query inside the 1st query because I want this to be synchronous.
Is there any way to access the variables that are set inside the first query from outside that query??
Here's the code, given that I'm connected to the database already:
var result;
var updateQuery;
for (var i = 0; i < 5 ; i++) {
connect.query("SELECT * FROM table1 WHERE id = " + i, function(err, result) {
result = result[0];
updateQuery = "UPDATE table2 SET column1 = " + result;
});
connect.query(updateQuery, function(err, result) {
console.log(result);
});
}

Can't access all values of array

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);
});

Get json array from sub mongoose query

I have a sub query in mongoose need to get array out of sub query and attach to main json out put/ object.
my first query get user info which contains blocked_users array which is nothing but array of user id's.
i my second query we get profile details of blocker_users array and append to main user object in blocked_users.
var userId = ObjectID(req.body.user_id);
//Get user
newUserModel.findById(userId, function(err, user){
if(err){
utils.getResponse(res, req.url, messages.failure, "");
} else {
var userInfo = {};
var blcked_contacts;
//get users details from blocked contacts userid's array
newUserModel.find({'_id': {$in:user.blocked_contacts}}, function (err,blocked_users) {
if(blocked_users){
//blcked_contacts.push(blocked_users);
console.log(blocked_users);
return;
};
/*else{
blcked_contacts = [];
}*/
});
userInfo['blocked_contacts'].push(blocked_users);
userInfo['user_id'] = user.id;
userInfo['country_code'] = user.country_code;
//userInfo['blocked_contacts'].push(blcked_contacts);
//userInfo['blocked_contacts'] = user.blocked_contacts;
var userData = Array();
}
});
Don't really know what you're looking for. But saw a problem in your code. You've assigned the blocked_users to the blocked_contacts field outside the find method.
Since these calls are asynchronous in nature, it might happen that the assignment takes place even before the documents are fetched from MongoDB. So you should write your assignment statements inside the find methods' callback, just the way Medet did.
Noticed few mistakes in your code like trying to use .push on an object. You cant do
userInfo['blocked_contacts'].push(blocked_users); // incorrect as userInfo is an empty object and you dont have an array defined for userInfo['blocked_contacts']
You probably get cannot push into undefined error for this. So instead do
userInfo['blocked_contacts'] = blocked_users;
Also you have to do this inside the second find() as blocked_users is only available inside it. So your final query should be something like
var userId = ObjectID(req.body.user_id);
//Get user
newUserModel.findById(userId, function(err, user){
if(err){
utils.getResponse(res, req.url, messages.failure, "");
} else {
var userInfo = {};
//get users details from blocked contacts userid's array
newUserModel.find({'_id': {$in:user.blocked_contacts}}, function (err,blocked_users) {
if(blocked_users){
userInfo['user_id'] = user.id;
userInfo['country_code'] = user.country_code;
userInfo['blocked_contacts'] = blocked_users; // assign blocked_users into userInfo
console.log(userInfo) // Your required object
} else {
userInfo['user_id'] = user.id;
userInfo['country_code'] = user.country_code;
userInfo['blocked_contacts'] = []; // assign null array if no blocked users fould
}
});
var userData = Array();
}
});
The result of console.log should be an object like this
{
user_id : "..id of searched user...",
country_code : "..country code of searched user..",
blocked_contacts : [<array containing detais of all blocked users>] // null array if no users found
}

NodeJS MSSQL WHERE IN Prepared SQL Statement

I am use nodejs npm package sql
I currently have an array of product skus like so..
var skus = ['product1', 'product2', 'product3'];
My sql store in a file as follows...
SELECT *
FROM stock AS s
WHERE s.sku IN (#skus)
Then I also have my prepared statement code as follows..
var connection = new sql.Connection(config, function(err) {
var ps = new sql.PreparedStatement(connection);
//Add params
if(params != undefined){
for(var key in params){
ps.input(key, sql.VarChar(200));
}
}
ps.prepare(sqlstatement, function(err) {
ps.execute(params, function(err, data) {
callback(null, data);
ps.unprepare(function(err) {
});
});
});
});
}
skus is contained correctly within the params object as the statement works fine when I am using it for simple WHERE X = #YI am just struggling with how I need pass the array of skus to allow them to work in the prepared statement.
I am amend the string using split and join to comma seperate them etc etc but I can't get these methods to work.
I assumed that I would need the param string to look like the following 'product1','product2','product3'.
would be also useful if someone could shed some light on how to debug the completed prepared statement so I can see what is actually being queried to SQL (with params inplace)
Many thanks in advance!
It appears that the sql object (i.e. the mssql module) has no attribute to handle arrays of anything. Moreover, specifying a scalar type in the call to ps.input similarly does not work.
The next best thing is to build keys for your array of parameters into your sql statement itself:
var connection = new sql.Connection(config, function(err) {
var ps = new sql.PreparedStatement(connection);
// Construct an object of parameters, using arbitrary keys
var paramsObj = params.reduce((obj, val, idx) => {
obj[`id${idx}`] = val;
ps.input(`id${idx}`, sql.VarChar(200));
return obj;
}, {});
// Manually insert the params' arbitrary keys into the statement
var stmt = 'select * from table where id in (' + Object.keys(paramsObj).map((o) => {return '#'+o}).join(',') + ')';
ps.prepare(stmt, function(err) {
ps.execute(paramsObj, function(err, data) {
callback(null, data);
ps.unprepare(function(err) {
});
});
});
});
}

Categories