I am trying to develop an API in node.js, express and mysql. I need return a json with subnodes/sub arrays. First make a query select in mysql, and this query return a array with my products. now i need itinerate this array (arrayProducts), get Id of current product and make other query select with this id in other table. When the second query return other array (arrayColors), and i make a for in this array and push each color in other array (arrayColorsAux) but when finish the second for (of second array) arrayColorsAux is emty. this is my code:
const express = require('express')
const routes = express.Router()
var mysql = require('mysql');
var pool = mysql.createPool({
host: 'localhost',
user: 'exampleUser',
password: 'examplePass',
database: 'exampleDb'
});
routes.get('/productos/cat/:id', (req, res) => {
var id = req.params.id;
pool.query('SELECT * FROM productos WHERE id_producto_categoria = ? and borrado=0', [id],
function (err, pro) {
arryaPproductos = pro;
for (let index = 0; index < arryaPproductos.length; index++) {
var element = arryaPproductos[index];
var idPro = element.Id;
pool.query('SELECT * FROM productos_colores WHERE id_producto = ?', idPro, function (err, col) {
element.colores = col;
console.log("Array: ", arryaPproductos);
//here show nice array
});
}
//here return empty array
res.json(arryaPproductos);
});
})