NodeJS - how can get mysql result with executed query? - javascript

I am new in NodeJS with mysql (npm install mysql).
When I try to execute query like
connection.query("select ?? from users where id = ?",[["id","fname","lname"],req.body.userid],function (err, rows) {
**here I want query which above executed**
});
I want query in callback function which executed.
How can I get it??.

var c = connection.query("select ?? from users where id = ?",[["id","fname","lname"],req.body.userid],function (err, rows) {
console.log(c.sql)
});

connection.query("select ?? from users where id = ?",[["id","fname","lname"],req.body.userid],function (err, rows) {
res.send(rows);
});
also in preference swith the string query to :
"select id,fname,lname from users where id = '"+req.body.userid+"'"

Related

How can I put the row number of a database in a variable

there is my problem :
{
const row_nb = con.query("SELECT COUNT(*) FROM Users WHERE username = '"+username_ins+"'");
console.log(""+row_nb);
}
but I dont have the row number why ?
it return [Object object]
And it's in javaScript
con.query is an async method you have to pass the callback to get the result.
var sql = "SELECT COUNT(*) as usersCount FROM Users WHERE username = ?"
con.query(sql, [username_ins], function(err, rows, fields) {
if (err) throw err;
console.log('Query result: ', rows[0].usersCount);
});

Express passing arrays into sql (express/mssql/react)

I am trying to upload two arrays into my sql database.
This is what I have come up with.(this is my server.js using a endpoint from my client side)
My express
app.post("/post-question-answers", async (req, res) => {
console.log("!called");
try {
await sql.connect(config);
// create Request object
var request = new sql.Request();
let results = req.body.results;
let questions = [];
let answers = [];
results.forEach(element => questions.push(element.question));
results.forEach(element => answers.push(element.answer));
for (var i = -1; i < results.length; i++) {
request.input("Question", sql.VarChar, questions[i]);
request.input("Answer", sql.VarChar, answers[i]);
request.execute("dbo.AddQuestionResponses", function(err, recordset) {
if (err) console.log(err);
// send records as a response
res.json(recordset);
});
}
} catch (e) {
console.log(e);
}
});
My sql stored procedrue
alter procedure AddQuestionResponses
#Question nvarchar (50),
#Answer nvarchar (50)
as
insert into QuestionResponses(QuestionWhenAnswered, QuestionResponse)
values (#Question ,#Answer )
However this throws
RequestError: The parameter name Question has already been declared. Parameter names must be unique
I believe this is because
request.input("Question", sql.VarChar, questions[i]);
request.input("Answer", sql.VarChar, answers[i]);
need to be unique and as they are in a for loop they are repeated within the statement. Is there a way in which I can make this a valid transaction with the database and so that these are unique.
Thankyou for your time :)
I solved this issue by putting
var request = new sql.Request();
within the for loop.

NodeJS Returning 'undefined' In MySQL Query Function

I have a function that queries SQL to get a string called Prefix.
function getPrefix(Guild) {
let query = "SELECT Prefix FROM Guilds WHERE GuildId=?";
Connection.query(query, [Guild.id], (err, result) => {
if (err) throw err;
return result[0].GuildPrefix;
});
};
Whenever I print the Prefix out (console.log(result[0].Prefix);), it logs it fine - however, whenever I return it and then attempt to call the function, it always returns undefined.
I am using Node JS Version 10.15.1 & I am using MariaDB Version 10.1.37 on the Raspbian stretch of Debian. Please comment if I have left any other information out. Thanks.
In Nodejs the functions related to mysql are always asynchronous which means they will either not return anything or will retuen undefined.
So the solution is to use a callback function.
Eg.
function getPrefix(Guild, callback) {
let query = "SELECT Prefix FROM Guilds WHERE GuildId=?";
Connection.query(query, [Guild.id], (err, result) => {
if (err){
callback(JSON.stringify(err));
};
callback(JSON.stringify(result));
});
};

REST API - Node, Express, MySQL - How can I filter a JSON (from DB) return by passing a limited number of objects via URL

I'm building a REST API, using Node, Express, MySQL.
When requesting a list of Node from the http://localhost:3000/Node endpoint,
I would like to limit these to only 25 initial records.
This could be accomplished with a request like GET http://localhost:3000/Node?maxRecords=25.
My routes\Nodes file is:
var express = require('express');
var router = express.Router();
var Node=require('../models/Node');
router.get('/:id?',function(req,res,next){
if(req.params.id){
Node.getNodeById(req.params.id,function(err,rows){
if(err)
{
res.json(err);
}
else{
res.json(rows);
}
});
}
else{
Node.getAllNodes(function(err,rows){
if(err)
{
res.json(err);
}
else
{
res.json(rows);
}
});
}
});
module.exports=router;
And in my models\Node.js (that is passing queries to db) is:
var db=require('../dbconnection');
var Node={
getAllNodes:function(callback){
return db.query("Select * from node_link",callback);
},
getNodeById:function(id,callback){
return db.query("select * from node_link where id=?",[id],callback);
}
}
module.exports=Node;
In your models/Node.js:
getAllNodes: function(maxRecords, callback) {
return db.query("Select * from node_link LIMIT ?", [maxRecords], callback);
}
You can use LIMIT in the query.
http://www.mysqltutorial.org/mysql-limit.aspx
The LIMIT attribute in your query will help, it will limit the number of rows outputted.
So, with this in mind, your query should look like:
SELECT * FROM node_link LIMIT 10
If you want more rows, just increase the 10 by whatever you want 😊.

Access to parent records in nested MySQL Queries

I have a problem with MySQL nested queries. First i want get all products, then in a nested query, iterate over all products (each product is a JSON) and for each product get their images adding a key 'images' to the current product.
exports.findAll = function(callback) {
var Database = require('../config/database.js')
var DBConnection = new Database()
var connection = DBConnection.connect()
connection.query('SELECT * FROM product', function(err, records, fields) {
var products = records
for(var i=0; i<products.length; i++) {
connection.query('SELECT Image FROM product_images WHERE Product = ?', [products[i].Id],
function(err, images, fields) {
console.log(products[i])
})
}
DBConnection.disconnect()
callback(err, products)
})
}
In the nested query, products[i] is undefined and can't add the images. ¿How can i solve this?
If a first get the records in the route, and then get the images calling to another function passing the records getted and iterate over they, maybe works, but i wanna know if exists a more 'easy' way.
Thanks.
Solved iterating only with for each:
exports.findAll = function(callback) {
var Database = require('../config/database.js')
var DBConnection = new Database()
var connection = DBConnection.connect()
var query = 'SELECT * FROM product'
connection.query(query, function(err, products) {
products.forEach(function(cur) {
var query = 'SELECT Image FROM product_images WHERE Product = ?'
connection.query(query, [cur['Id']], function(err, images) {
cur['images'] = images
callback(err, products)
})
})
DBConnection.disconnect()
})
}
Can someone explain me why works with forEach and don't with normal for or for in?

Categories

Resources