How to get the answer of a mysql request and stock it? - mysql

I'm building a server and i'm trying to know if a key is in my sql DB.
I want to know if it is possible to get only the value of sql request or do I need to parse it?
function checkKey(key) {
var sqlcheck = "SELECT customerID from authentification where discord_key =
?";
console.log("in function");
DB.query(sqlcheck, [key], function (err, result) {
if (err) throw err;
console.log(result);
});
}
this is what I get :
RowDataPacket { customerID: 'cus_ET5gXP7p7Tafmf' }
but I am looking to get only:
cus_ET5gXP7p7Tafmf
Thank you for your help!

generally
result[0].customerID
however in your example it looks like
result.customerID

Related

How to print the actual query which is being excicuted on node js on console

Hi I am trying the following code
userwallet.post('/api/user/wallet/create',verifyToken,(req,res)=>{
jwt.verify(req.token,'secretkey',(err,authData)=>{
if(err){
console.log(err)
return res.sendStatus('403');
}else{
mysqlConnection.query("INSERT into user_wallets(uuid,user_uuid,balance,status,created_at,updated_at) VALUES(?,?,?,?,?,?)",[uuid(),authData.id,0,'ACTIVE',new Date(),0],(err,rows,fields)=>{
if(!err)
return res.json({
message:"Successfull",
added:rows,
authData
});
console.log('Wallet creation error:',err)
return res.sendStatus('403');
});
}
});
});
There is some trouble of executing this code on the remote machine It is not querying so I am trying to out put the query on console i was going through this answer that is not helpful
NodeJS - how can get mysql result with executed query?
Any suggestions? For troubleshooting
You need to assign connection.query to a variable e.g. query and then can get the sql by query.sql. For more detail
var post = {id: 1, title: 'Hello WORLD'};
var query = connection.query('INSERT INTO TABLENAME SET ?', post, function(err,
result) {
// SOMETHING
});
//HERE YOU CAN GET QUERY
console.log(query.sql);

Making a Discord Verification System

So I am trying to make a discord bot with 2 commands:
!addver {verification code} & !verify {code}
the codes will be stored in a MySQL database hosted on my computer using XAMPP. I have successfully gotten it to add the verification code to the database, but right now I am having trouble trying to get it to read the table, and do what I am telling it to.
This is the verify command that I have at the moment:
if (isCommand("verify",message)) {
if (err) throw err;
con.query("SELECT Code FROM verf", function (err, result, fields) {
if (err) throw err;
console.log(result[1].code);
});
}
And this is my database. Ignore Name, thats just for my own record of who makes a verification code:
https://gyazo.com/324b4537a975268e8c5ea38edd08767b
EDIT:
Got the code working to find the code that people enter, but cant get it to do anything afterwards. The final if is where the issue is at the moment
if (isCommand("verify",message)) {
var fsql = "SELECT * FROM `verf` WHERE `Code` LIKE ?";
var vals = [
[args[0]]
];
con.query(fsql, [vals], function (err, result) {
if (err) throw err;
console.log(result);
if (result.RowDataPacket.Code === (args[0])) return message.channel.send("You have entered an invalid code!")
message.member.addRole(WHITELISTED);
})}

How to push a json object in array in mongodb with loopback?

Here is my efforts :
async.waterfall([
function(nextCall){
MongoClient.connect(url, function(err, db) {
if (err) throw err;
const dbo = db.db("testmdb");
const criteria = {"_id":ObjectId(id)};
console.log("paymentInof[] ::: ",paymentInfo)
let obj = paymentInfo[0];
const query = {
$push:{payment:obj}
};
dbo.collection("Invoice").update(criteria, query);
db.close();
nextCall(null,{code:200});
});
}
],function(err,results){
if(err) return err;
if(results.code === 200)
console.log(chalk.blue(' ::: all done ::: '));
next();
});
Input from api explorer :
{
"payment":[{"transaction_at":"2018-02-12T06:04:35.279Z","paid_amount":350,"patient_id":"1233sssdd33","patient_urn":"214125","invoice_amount":700,"user":"me"}],
"updated_by": "me"
}
Everything working fine but unable to push instead overwriting the existing object in payment array.
While from mongo shell it is working fine.
Please help me , where I am doing wrong ?
Thanks.
I think you need to check mongoose update upsert option.
Update options
There are several option values that can be used with an update
multi - update all records that match the query object, default is false (only the first one found is updated)
upsert - if true and no records match the query, insert update as a new record
raw - driver returns updated document as bson binary Buffer, default:false
Please check the documentation to here.
Use following code,
async.waterfall([
function(nextCall){
MongoClient.connect(url, function(err, db) {
if (err) throw err;
const dbo = db.db("testmdb");
let criteria = {"_id": ObjectId(id)};
let obj = paymentInfo[0];
let query = { $push: { payment: obj } }
dbo.collection("Invoice").update(criteria, query, {upsert:true});
db.close();
nextCall(null,{code:200});
});
}
],function(err,results){
if(err) return err;
if(results.code === 200)
console.log(chalk.blue(' ::: all done ::: '));
next();
});
Also please check the similar type of question to here and here.
Hope this will help you!!

JSON result is showing command of SUM MySQL

I'm getting an effective return calculation of all values column my MYSQL table but when i went to check my api result; the column value sum command is appearing in the result of the JSON.
[
{
"SUM(producFinalPrice)": 6000
}
]
This my router get data from my data base.
router.get('/sell/home-card-last-sell-compared-to-the-previous-day', function (req, res) {
connection.query('SELECT SUM(producFinalPrice) FROM new_sell',
function (err, lastSellComparedToThePreviousDayCardHome, fields) {
if (err) {
throw err;
}
res.send(lastSellComparedToThePreviousDayCardHome);
}
);
});
`
Making my mistake clearer, i'm making the final request from the previous query in AJAX; Through this way.
$(function () {
$.ajax({
type: "GET",
url: "/sell/home-card-last-sell-compared-to-the-previous-day",
success: function (lastSellComparedToThePreviousDayCardHome) {
var $lastSellComparedPreviousDay = $('#last-sell-compared-to-the-previous-day');
$.each(lastSellComparedToThePreviousDayCardHome, function (i, SellPreviousDay) {
$lastSellComparedPreviousDay.append('<li>R$ ' + SellPreviousDay.producFinalPrice + '.</li>');
});
console.log('Sucess return to Last Sell Previous Day!', lastSellComparedToThePreviousDayCardHome);
}
});
});
Basically that's it I could not find anything that would help me..
Thanks for helping me out ;]
Use an alias:
connection.query('SELECT SUM(producFinalPrice) AS productFinalSum FROM new_sell', ...
^^^^^^^^
Then when you parse your JSON in Node check for the productFinalSum key. Actually, I think you could even use SUM(productFinalSum) to access your JSON, but it looks awkward.

Store mysql query rows in variable for later use

I'm doing a monitoring system project in which I have Arduino sensors data being sent to a node.js server (thru GET requests) and then stored in a MySQL DB.
Whenvever I successfully send data to the server, it connects to the MySQL DB and queries the last 5 received records to do some processing.
Therefore, I need to store the rows of those 5 records in a variable for later use. Meaning that I have to get rows from a connection.query in a variable.
I read that the fact that I'm not able to do this is because node.js being async. So my questions are:
Is it possible to do the described tasks the way I'm trying?
If not, is there any other way to do so?
I'm not putting the whole code here but I'm running a separated test that also doesn't run properly. Here it is:
var mysql = require('mysql');
var con = mysql.createConnection({
host : "127.0.0.1",
user : "root",
password: "xxxx",
database: "mydb",
port : 3306
});
var queryString = "SELECT id, temp1, temp2, temp3, temp4, level_ice_bank, flow FROM tempdata ORDER BY id DESC LIMIT 5";
con.connect(function(err) {
if (err) throw err;
});
var result_arr = [];
function setValue (value) {
result_arr = value;
}
con.query(queryString, function (err, rows, fields) {
if (err) throw err;
else {
//console.log(rows);
setValue(rows);
}
});
console.log(result_arr);
It logs:
[]
But if I uncomment console.log(rows); it logs what I need to store in the variable result_arr.
Thanks in advance to all.
You're seeing this behaviour because con.query(...) is an asynchronous function. That means that:
console.log(result_arr);
Runs before:
con.query(queryString, function (err, rows, fields) {
if (err) throw err;
else {
//console.log(rows);
setValue(rows);
}
});
(Specifically, the setValue(rows) call)
To fix this in your example, you can just do:
con.query(queryString, function (err, rows, fields) {
if (err) throw err;
else {
setValue(rows);
console.log(result_arr);
}
});
If you want to do more than just log the data, then you can call a function which depends on result_arr from the con.query callback, like this:
con.query(queryString, function (err, rows, fields) {
if (err) throw err;
else {
setValue(rows);
doCleverStuffWithData();
}
});
function doCleverStuffWithData() {
// Do something with result_arr
}