Make query after query with nodejs and sequelize - mysql

I want to make a query after another query in node.js with sequqlize. Second query iterate ower the first elements query result.
The code:
exports.index = function(req, res) {
sqldb.sequelize.query("select * from food", {type: sqldb.sequelize.QueryTypes.SELECT})
.then(function (food) {
for (var i = food.length; i--;) {
sqldb.sequelize.query("select i.name_ingredient " +
"from food_incredients as fi, " +
"ingredients as i " +
"where fi.food_id = " + food[i].id + " and " +
"i.id = fi.ingredient_id;",
{type: sqldb.sequelize.QueryTypes.SELECT}).then(function (ingredients) {
food[i]["ingredients"] = ingredients;
});
}
res.status(200).json(food);
}
);
At the line when I try to add "infredients" field I reveive an error that the "food[i]" object is undefined. How can I fix this problem and return the "food" with ingredients for every elements?
Thanks

Related

Query is working on phpmyadmin but not in express

I have a problem with a MySQL query, I'm making a controller where I need a filter on the front (React). The controller is made with params inside the route, but is not working when I try to test it with Postman, but if I make the same exact query on phpmyadmin works perfectly.
Controller:
let { tabla, nameUno, fechaIni, fechaFin, nameDos, nameTres, nameCuatro } =
req.params;
conn.query(
// SELECT * FROM tyt_finan WHERE tf_fecha_r BETWEEN '2022-05-31' AND '2022-06-01' AND tf_city IN ('Bogota') AND tf_estado = 'Pendiente' AND tf_campana = 'IN'
"SELECT * FROM " +
tabla +
" WHERE " +
nameUno +
" BETWEEN " +
fechaIni +
" AND " +
fechaFin +
" AND " +
nameDos +
" IN ('') AND " +
nameTres +
" = ? AND " +
nameCuatro +
" = ?",
[req.params.value1, req.params.value2, req.params.value3],
Routes
routes.get(
"/searchAll/:tabla/:nameUno/:fechaIni/:fechaFin/:nameDos/:value1/:nameTres/:value2/:nameCuatro/:value3",
defaultController.searchAll
);
And this is the GET petition that I'm sending on Postman:
http://localhost:9000/searchAll/tyt_finan/tf_fecha_r/'2022-05-31'/'2022-06-01'/tf_city/'Bogota','Barranquilla'/tf_estado/'Pendiente'/tf_campana/'IN'
Use parameters for the variables. It's also easier to use a template literal than concatenation to construct the SQL string with variables for the table and column names.
You also had more values in your parameters array than ? in the SQL. I've replaced IN ('') with = ? to use value1 there.
let {tabla, nameUno, fechaIni, fechaFin, nameDos, value1, nameTres, value2, nameCuatro, value3} = req.params;
conn.query(
`SELECT *
FROM ${tabla}
WHERE ${nameUno} BETWEEN ? AND ?
AND ${nameDos} = ?
AND ${nameTres} = ?
AND ${nameCuatro} = ?`, [fetchaIni, fechaFin, value1, value2, value3], (err, res) => {
if (!err) {
console.log(res);
}
});

How to query DynamoDB in AWS using a number partition key

I'm currently having trouble querying a DynamoDB table where the partition key, id, is of type number. This is for a wider project for my own Alexa Skill on AWS. My skill will take as input from the user, a unique id value, which is of slot type AMAZON.NUMBER.
I've looked at the documentation for query and nothing I've tried worked so I decided to start from scratch to a template.
Again, I am just trying to query a table for data based on a partition key called "id" that has a numeric value. The Code below is what I have managed to narrow down as the source of the error.
var params = {
TableName : "QueryTestTable",
KeyConditionExpression: "#pkey = :value",
ExpressionAttributeNames:{
"#pkey": "id"
},
ExpressionAttributeValues: {
":value": idNumber
}
};
return docClient.query(params, function(err,data) {
if (err) {
console.error("Unable to query. Error:", JSON.stringify(err, null, 2));
} else {
console.log("Query succeeded.");
console.log("data = " + JSON.stringify(data,null,2));
data.Items.forEach(function(item) {
console.log(" -", item.id + ": " + item.firstName);
results += item.id + " has name " +item.firstName + " " + item.lastName + ".\n";
});
}
if (results)
speakOutput = results;
else
speakOutput = "Sorry, no result for " + idNumber +" was found in the database.";
return handlerInput.responseBuilder
.speak(speakOutput)
.reprompt()
.withSimpleCard(SKILL_NAME, speakOutput) //added to generate video output.
.getResponse();
})
I'm just using a simplified version of my table for now. But the above code snippet. For some reason, It keeps skipping to the no entries found in the database statement.

Cannot read property 'json' of undefined

why is it not getting result ? The sql query is simple and correct and works in mysql
const getDateBw = (InvoiceDate1, InvoiceDate2, err, req, res) => {
let startDate = new Date(InvoiceDate1);
let endDate = new Date(InvoiceDate2);
let formattedDate1 = JSON.stringify(dateFormat(startDate, "yyyy-mm-dd"));
let formattedDate2 = JSON.stringify(dateFormat(endDate, "yyyy-mm-dd"));
console.log(formattedDate1);
db.query(
"SELECT * FROM dashboard WHERE Invoice_Date BETWEEN " +
formattedDate1 +
" " +
"AND " +
formattedDate2
).then(function (myTableRows) {
res.json({
myTableRows,
});
});
};
getDateBw("2009-05-21", "2021-01-01");
{"level":50,
"time":1598543997608,
"pid":10772,
"hostname":"Ghadi-Mdallal",
"stack":"TypeError: Cannot read property 'json' of undefined\n at C:\\Users\\LENOVO\\Desktop\\Dashboard-V1\\empServer\\handlers\\user.controllers\\user.controllers.js:29:9\n at processTicksAndRejections (internal/process/task_queues.js:97:5)",
"type":"Error",
"msg":"Cannot read property 'json' of undefined"
}
You are not passing "res" in getDateBw("2009-05-21", "2021-01-01");
How will res.json work inside? It will give "Cannot read property 'json' of undefined" error.

Extract Value from Json string in Ionic 2

I am using OAuth2 for authorization in my Ionic 2 App and the decoded token response(which I am getting from the BASE64.decode() function) is like the below(key-value form).I am storing it in a variable called 'tokendata' of type 'any'. Now I want to extract values from this decoded token. Now if I simply do 'tokendata.personnelnbr', it is not working. Also if I do a 'json.parse(tokendata) or a json.parse('tokendata'), store it in another variable say 'myVar' and then try to access 'myVar.personnelnbr', then also it is not working. Please help with the solution!
{
"client_id":"xxx",
"scope":"user_profile",
"sub":"yyy",
"amr":"external",
"auth_time":1499753830,
"idp":"eso_enterprise",
"upn":"yyy",
"email":"yyy",
"samaccount_name":"yyy",
"peoplekey":"1169",
"personnelnbr":"1108",
"given_name":"Deblina",
"sn":"Dutta Chowdhury",
"exp":1499,
"nbf":1499
}
The method where I am trying to access the 'personnelnbr' field is given below:
private initializeApp(): void
{
this.platform.ready().then(() => {
console.log("Before login Deblina");
/**
* Read in app configuration, get an oAuthV1 ESO token, register device with REBAR Notification Services
*/
this.configService.Initialize().subscribe(
() => this.esoService.getV2Token().subscribe(
(v2Token) => {
this.tokendata = BASE64.decode(v2Token);
alert("Token Deblina decoded: " + BASE64.decode(v2Token));
console.log("Token Deblina decoded: " + BASE64.decode(v2Token));
this.concatenatedToken = "'" +this.tokendata+ "'";
alert(this.concatenatedToken);
console.log(this.concatenatedToken);
this.myVar = JSON.parse(this.tokendata);
alert("Now:" + this.myVar.personnelnbr);
console.log("Now:" + this.myVar.personnelnbr);
this.myVar = JSON.parse(this.concatenatedToken);
alert("Now:" + this.myVar.personnelnbr);
console.log("Now:" + this.myVar.personnelnbr);
},
(error) => console.log(error),
() => { this.nav.setRoot(HomePage)}
),
(error) => console.log(error)
);
});
}
If you just want to to extract value, you can do this:
let datas = {
"client_id":"xxx",
"scope":"user_profile",
"sub":"yyy",
"amr":"external",
"auth_time":1499753830,
"idp":"eso_enterprise",
"upn":"yyy",
"email":"yyy",
"samaccount_name":"yyy",
"peoplekey":"1169",
"personnelnbr":"1108",
"given_name":"Deblina",
"sn":"Dutta Chowdhury",
"exp":1499,
"nbf":1499
};
for (let key in datas) {
console.log(key + " => " + datas[key]);
}

NodeJS - MySQL query error

My query works fine if the person exist in my table, but if he/she does not; the NodeJS will give me an error.
function ClientConnected(remoteClient)
{
debugLog(remoteClient.name + " connected to the server. (ID: " + remoteClient.networkId + ") Loading player data..");
sql.query('SELECT * FROM `players` WHERE `character_name` = ?', [remoteClient.name], function(err, rows)
{
if(err)
{
debugLog('[DB] Error when loading ' + remoteClient.name + "'s (" + remoteClient.networkId + ') data: ' + err.code);
} else {
players[remoteClient.networkId] = {
'a_socialid' : rows[0].account_socialid,
'i_money' : rows[0].inventory_money,
};
debugLog("Successfully loaded " + remoteClient.name + "'s (" + remoteClient.networkId + ") data..");
}
});
}
events.Add("ClientConnected", ClientConnected);
If someone joins with the name that already exists in the table, it will load the players data:
But if not, it gives me an error. (TypeError, undefined, blabla)
You need to check that a record was returned. Maybe something like this:
if(err)
{
debugLog('[DB] Error when loading ' + remoteClient.name + "'s (" + remoteClient.networkId + ') data: ' + err.code);
} else if (rows.length === 0) {
debugLog('Nothing returned from database');
} else {
// ...
}
Presumably the err result would only give you feedback on the actual query, not the data it returns.