how to create array with push in node.js - javascript

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?

Related

Couldn`t display callback buttons (Telegraf lib.) using forEach method

My task is to add callback buttons for each element of array which i get from MySql table.
let select = `SELECT Bike_num FROM rent.Bike_Status_num where Last_Station = 1 and B_Status = 'OK';`
con.query(select, function (err, result) {
if (err) {
console.log(err);
return err;
} else {
let replyButtons = [];
let bikes_free = result;
ctx.reply('Chose bicycle',
Markup.inlineKeyboard([
[Markup.button.callback(`${bikes_free[0].Bike_num}`, `${bikes_free[0].Bike_num}`),
Markup.button.callback(`${bikes_free[1].Bike_num}`, `${bikes_free[1].Bike_num}`),
Markup.button.callback(`${bikes_free[2].Bike_num}`, `${bikes_free[2].Bike_num}`),
Markup.button.callback(`${bikes_free[3].Bike_num}`, `${bikes_free[3].Bike_num}`)],
[Markup.button.callback(`${bikes_free[4].Bike_num}`, `${bikes_free[4].Bike_num}`),
Markup.button.callback(`${bikes_free[5].Bike_num}`, `${bikes_free[5].Bike_num}`),
Markup.button.callback(`${bikes_free[6].Bike_num}`, `${bikes_free[6].Bike_num}`),
Markup.button.callback(`${bikes_free[7].Bike_num}`, `${bikes_free[7].Bike_num}`)]
]))
I don`t know how to display this buttons using forEach method or any other convenient method.
Tried 2 ways, but got an errors.

javascript- pushing resultset from database to array failed

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

Appending new Elements to Objects in Array

I've been puzzling over this loop for a few days and can't quite get to what I need.
I loop over my array of search results (mdb_results) and extract from each object a .name to use as a _search term in a Google CSE Image Search.
Th CSE returns another array (cse) which I want to append to the object from which I extracted the _search term (mdb_results[i]).
router.get('/json', function(req, res, next) {
var ImageSearch = require('node-google-image-search');
MongoClient.connect(url, function(err,db){
db.collection('mycatalog')
.find({$text: {$search:"FOO" }})
.toArray(function(err, mdb_results){
for (var i=0; i<mdb_results.length; i++){
var _search = mdb_results[i].name ;
ImageSearch(_search, function(cse){
// How to add cse.img to mdb_results[i].images ??
// mdb_results[i].images = cse;
// gives undefined
},0,2);
};
res.send(mdb_results);
});
});
});
My initial mdb_results looks like this.
[{"name":"FOO"},{"name":"FOOOO"}]
I'm trying to achieve something like this,
[{"name":"FOO",
"images":[{"img1":"http://thumbnail1"},{"img2":"http://thumbnail2"}]
},
{"name":"FOOOO",
"images":[{"img1":"http://thumbnaila"},{"img2":"http://thumbnailb"}]
}]
Can anyone show me how to achieve this?
Thanks
The issue is that you're expecting an asynchronous operation to work synchronously:
router.get('/json', function(req, res, next) {
var ImageSearch = require('node-google-image-search');
MongoClient.connect(url, function(err,db){
db.collection('mycatalog')
.find({$text: {$search:"FOO" }})
.toArray(function(err, mdb_results){
for (var i=0; i<mdb_results.length; i++){
var _search = mdb_results[i].name ;
// This search is asynchronous, it won't have returned by the time
// you return the result below.
ImageSearch(_search, function(cse){
// How to add cse.img to mdb_results[i].images ??
// mdb_results[i].images = cse;
// gives undefined
},0,2);
};
// At this point, ImageSearch has been called, but has not returned results.
res.send(mdb_results);
});
});
});
You're going to need to use promises or the async library.
Here's an example:
router.get('/json', function(req, res, next) {
var ImageSearch = require('node-google-image-search');
MongoClient.connect(url, function(err,db){
db.collection('mycatalog')
.find({$text: {$search:"FOO" }})
.toArray(function(err, mdb_results){
// async.forEach will iterate through an array and perform an asynchronous action.
// It waits for you to call callback() to indicate that you are done
// rather than waiting for it to execute synchronously.
async.forEach(mdb_results, function (result, callback) {
ImageSearch(result.name, function(cse){
// This code doesn't get executed until the network call returns results.
result.images = cse;
// This indicate that you are done with this iteration.
return callback();
},0,2);
},
// This gets call once callback() is called for each element in the array,
// so this only gets fired after ImageSearch returns you results.
function (err) {
res.send(mdb_results);
});
});
});

Make multiple request in Mongoose

I'm trying to reach different select's from another select with MongoDB database with mongoose to redirect to Emberjs front-end.
If the text above it's not clear, look at the schema of the database:
// I already get the exam content given an id
Exam:{
...
collections:[{
question: Object(Id)
}]
...
}
and in the question schema it's:
// I want to get content of this giving an id
question:{
...
questions: String, // I want to get this given an Id exam
value: Number // and this
...
}
I tried to get it getting the objects id of the collections and then make a for to extract each question, and save the returned values into a json variable like this:
Test.findById(id, 'collections', function(err, collections){
if(err)
{
res.send(err);
}
var result ={}; //json variable for the response
// the for it's with the number of objectId's that had been found
for(var i = 0; i < collections.collections.length; i++)
{
// Send the request's to the database
QuestionGroup.findById(collections.collections[i].id, 'questions').exec(function(err, questiongroup)
{
if(err)
{
res.send(err);
}
// save the results in the json
result.questiongroup = questiongroup;
// prints questions
console.log(result);
});
// it return's {}
console.log(result);
}
// also return {}
console.log(result);
res.json({result: result});
});
It's there a way to save the requests into a variable and return it like a json to the front end?
since the query within the loop executes in async manner you'll have send response once everything finished execution.
For eg.
Test.findById(id, 'collections', function(err, collections) {
if (err) {
res.send(err);
}
var result = []; //json variable for the response
function done(result) {
res.json({
result
});
}
for (var i = 0, l = collections.collections.length; i < l; i++) {
// i need needs to be in private scope
(function(i) {
QuestionGroup.findById(collections.collections[i].id, 'questions').exec(function(err, questiongroup) {
if (err) {
res.send(err);
}
// save the results in the json
result.push(questiongroup);
if (l === i + 1) {
done(result);
}
});
})(i);
}
});
NOTE: untested, and you might have to handle errors appropriately

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