javascript- pushing resultset from database to array failed - javascript

I'm running a query to fetch the list of new users. Query is correct. It returns 15 users. I push the resultset into a javascript array but only the last record from the resultset is getting saved.
Here's my code:
var query = `SELECT *
FROM users
WHERE (status ='New')`;
var query = connection.query(query),
response = []; // this array will contain the result of our db query
query
.on('error', function (err) {
console.log(err);
})
.on('result', function (res) {
// it fills our array looping on each user row inside the db
response.push(res);
/*
for (var key in res) {
if (res.hasOwnProperty(key)) response.push(res[key]);
}
*/
})
.on('end', function () {
console.log('console')
});
As you can see response.push(res); is the line of code where I do this. Below that I have comment a few lines. I tried that option to push each row from the resultset but it ain't giving any results.

try a for loop
for(var i in res){
response.push(res[i]);
}

I maybe underestimate your test but you maybe check result at the wrong place.
You should do it on the 'end' callback.
.on('end', function () {
console.dir(res)
});

Related

how to create array with push in node.js

I will be select my data from MySQL then I loop this result and then I create an array with push. but I got two results after creating the array. the first array is empty and the second result is normal.
this is my code
app.all("/social-feed-reply", isUserAllowed, function (req, res) {
// console.log('......here');
// console.log(req.query);
// console.log('.......new test');
// console.log(req.query.id);
var sql = " SELECT * FROM books WHERE book_id IN(?) ";
db.query(sql, [req.query.id, 0], function (err, result, fields) {
if (err) throw err;
//here is i got normal result
var newArrays = [];
Object.keys(result).forEach(function (key) {
newArrays.push(result[key].book_id);
});
console.log(newArrays);
//when is console the newArrays then i got two result exemple :[] [ 7, 5 ]
});
});
how can I remove the empty array?

Express: MySQL query doesn't push code to a list

I have been trying to push the results of MySQL query to a list(shoppingList), but the shoppingList is always empty, even though I'm getting 2 results back.
I think the problem is somewhere with handling the promise, but I haven't been able to figure it out:
static async showShoppingList(userId) {
let shoppingList = [];
const sql =
"SELECT item_name, family_member_name FROM shopping_list WHERE user_id = (?)";
await db.promise().query(sql, [userId], function (err, results) {
for (const result of results) {
shoppingList.push(result)
console.log(shoppingList) // Here it appears with results
}
});
console.log(shoppingList) // Here it appears empty
return shoppingList;
}
That's because the callback function(err, results) is executed asynchronously, after the database has returned the results, whereas the other statement is executed synchronously:
db.promise().query sends the query to the database.
The empty shoppingList is written to the console and returned.
After the database has returned the results, the callback function is executed, writing the full shoppingList to the console.

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.

Javascript function doesn't return query result

I am trying to figure out why one of my queries won't return the value from a query...my code looks like this:
var client = new pg.Client(conString);
client.connect();
var query = client.query("SELECT count(*) as count FROM sat_scores")
// Don't use demo key in production. Get a key from https://api.nasa.gov/index.html#apply-for-an-api-key
function getNEO(callback) {
var data = '';
query.on('rows', function(rows) {
console.log("Row count is: %s", rows[0].count)
data += rows[0].count;
});
query.on('end', function() {
callback(data);
});
}
with that, getNEO returns a blank...but if I set var data = '4', then getNEO returns 4....the query should return 128 but it just returns a blank...
First of all, getNEO() doesn't return anything - I'm operating on the assumption that you call getNEO() exactly once for your query, and pass in a callback to handle the data, and that callback is what's not getting the appropriate data?
My typical recommendation for troubleshooting things like this is to simplify your code, and try and get really close to any example code given (for instance):
var client = new pg.Client(conString);
// define your callback here, in theory
client.connect(function (err) {
if (err) throw err;
var query = client.query("SELECT count(*) as count FROM sat_scores"),
function(err, result) {
if (err) throw err;
console.log(result.rows.length);
}
);
});
... I'm doing a couple things here you'll want to note:
It looks like the client.connect() method is asynchronous - you can't just connect and then go run your query, you have to wait until the connection is completed, hence the callback. Looking through the code, it looks like it may emit a connect event when it's ready to send queries, so you don't have to use a callback on the connect() method directly.
I don't see a data event in the documentation for the query object nor do I see one in the code. You could use the row event, or you could use a callback directly on the query as in the example on the main page - that's what I've done here in the interest of simplicity.
I don't see the count property you're using, and row[0] is only going to be the first result - I think you want the length property on the whole rows array if you're looking for the number of rows returned.
I don't know if you have a good reason to use the getNEO() function as opposed to putting the code directly in procedurally, but I think you can get a closer approximation of what you're after like this:
var client = new pg.Client(conString);
// define your callback here, in theory
client.connect();
function getNEO(callback) {
client.on('connect', function () {
var query = client.query("SELECT count(*) as count FROM sat_scores"));
query.on('end', function(result) {
callback(result.rowCount);
});
});
}
... so, you can call your getNEO() function whenever you like, it'll appropriately wait for the connection to be completed, and then you can skip tracking each row as it comes; the end event receives the result object which will give you all the rows and the row count to do with what you wish.
so here is how I was able to resolve the issue....I moved the var query inside of the function
function getNEO(state, callback) {
var conString = "postgres://alexa:al#alexadb2.cgh3p2.us-east-1.redshift.amazonaws.com:5439/alexa";
var client = new pg.Client(conString);
client.connect();
var data = '';
var query = client.query("SELECT avg(Math) as math, avg(Reading) as reading FROM sat_scores WHERE State = '" + state + "'");
console.log("query is: %s", query);
query.on('row', function(row) {
console.log("Row cnt is: %s", row.math);
console.log("row is: " + row)
data += row;
});
console.log("made it");
query.on('end', function() {
callback(data);
});
}

Processing database query in node.js

What's the correct way to process information from a database query after it has been retrieved.
Assuming the the below example that dataObj is just a js object that contains a field, name, which is defined, is this how I should be processing data in node.js?
EDIT:
forgot to mention that of course I can't return the data object because this is an async call.
function processData(dataObj){
if(dataObj.name == "CS"){
console.log("true");
}
}
function getData(anon)
var dat = .... sql query that works and its an object now that works correctly...
anon(dat);
}
getData(processData);
Here's a snippet of some code i'm working on using mongoose:
var db = mongoose.createConnection(uristring)
, mongoose = require('mongoose');
db.once('open', function(){
var recipientSchema = mongoose.Schema({
username: String,
recipientEmail: String
});
var Recipient = db.model('Recipient', recipientSchema);
Recipient.find( {username: user }, function(err, recipients){
res.json(recipients);
})
})
Hope that helps!
One of NodeJS' strengths is streaming support. I would expect from a proper SQL driver to give me one row at the time. If I want I can collect all of them, but most of the time I don't want all the rows in memory. Instead I would stream them one by one to a consumer.
My preferred DB code would look like...
var db = require('<somedriver>');
var sqlStatement = ".... sql query that works and its an object now that works correctly...";
var query = db.execute(sqlStatement);
query.on('row', function (row) {
// Do something with a row object...
console.log("This is a row", row);
});
query.on('done', function (err, rowcount) {
if (err) { throw err; } // or do something else...
console.log("Number of rows received", rowcount)
});
Hope this helps

Categories

Resources