I am trying to display specific data from a table in mysql using this code. I am in between using a for loop but it says that res or response is not defined. What do I need to edit or change in my code below?
function lowInventory() {
console.log("View all product that are low in inventory...\n");
for (var i = 0; i < response.length; i++) {
connection.query("SELECT stock_quantity (*) FROM products WHERE stock_quantity < 5", function (err, res) {
if (err) throw err;
//log all results of the SELECT statement
console.table(Response);
connection.end();
});
}
}
I need for it to display results of quantity that is less than 5 in node.js from my table.
change console.table(Response) to console.log(Response)
Related
I need to make 2 requests to my API to insert data in 2 different table:
Workflow:
request to get the last id + 1 => create the array I need (last_id, values) => two INSERT in MySql, 1st with varius data, 2nd with the array I created.
router.post("/addentry", function (req, res) {
let sql = "SELECT MAX(id) + 1 AS last_id FROM entries;"; // I get the id
let query = connection
.query(sql, (err, results) => {
if (err) throw err;
res.header("Access-Control-Allow-Origin", "*");
// put the id in a variable
var last_id = results[0].last_id;
var categoriesMap = req.body.categories;
var valCat = Object.values(categoriesMap);
// I create the array with other data
var catArray = valCat.map((item) => {
return [last_id, item];
});
})
.then((catArray) => {
let sql = `BEGIN; INSERT INTO entries (title,kindof) VALUES("${[
req.body.title,
]}","${req.body.kindof}");
INSERT INTO categories_main (entry_id, cat_id) VALUES ? ;
COMMIT;`;
let query = connection.query(sql, [catArray], (err, results) => {
if (err) throw err;
console.log(results);
res.header("Access-Control-Allow-Origin", "*");
res.send("Entry added to DB");
});
});
The first part works perfectly but with the second I get
TypeError: connection.query(...).then is not a function
Any idea how to do it?
Thanks
First things first, you should make sure that you use node-mysql2 instead of node-mysql. node-mysql2 has a built in functionality that helps making multiple queries inside a single connection. I have provided you this answer that exemplifies how to use it properly.
Moving forward, after you've done that, to be able to work with your result object, you will need JSON.
The following syntax is what you probably want to use:
var stringify = JSON.parse(JSON.stringify(results[0]));
for (var i = 0; i < stringify.length; i++) {
var last_id = stringify[i]["last_id"];
}
I need to make 2 requests to my API to insert data in 2 different table:
From code, I see that you are intending to do a single API call to the server and run 2 queries.
You can do .then only on a Promise, so as we can see connection.query is not returning a Promise and hence not then able.
Also you are setting response headers multiple times res.header("Access-Control-Allow-Origin", "*"); do this only once in a request cycle. So lets follow the callback approach instead of then.
let sql = "SELECT MAX(id) + 1 AS last_id FROM entries;"; // I get the id
let query = connection
.query(sql, (err, results) => {
if (err) {
res.header("Access-Control-Allow-Origin", "*");
return res.status(500).send({error:'server error'});
}
// put the id in a variable
var last_id = results[0].last_id;
var categoriesMap = req.body.categories;
var valCat = Object.values(categoriesMap);
// I create the array with other data
var catArray = valCat.map((item) => {
return [last_id, item];
});
let sql = `BEGIN; INSERT INTO entries (title,kindof) VALUES("${[
req.body.title,
]}","${req.body.kindof}");
INSERT INTO categories_main (entry_id, cat_id) VALUES ? ;
COMMIT;`;
let query = connection.query(sql, [catArray], (err, results) => {
if (err) {
res.header("Access-Control-Allow-Origin", "*");
return res.status(500).send({error:'server error'});
}
console.log(results);
res.header("Access-Control-Allow-Origin", "*");
res.send("Entry added to DB");
});
})
Here the complete solution, starting from what #SubinSebastian advised to me.
First of all I needed node-mysql2, that alows promises and therefore chained requests.
And then:
router.post("/addentry", function (req, res) {
let sql = "SELECT MAX(id) + 1 AS last_id FROM entries;";
connection.promise().query(sql)
.then((results) => {
// I get the value from results
var stringify = JSON.parse(JSON.stringify(results[0]));
for (var i = 0; i < stringify.length; i++) {
console.log(stringify[i]["last_id"]);
var last_id = stringify[i]["last_id"];
}
// I get some parameters and I create the array
var categoriesMap = req.body.categories;
var valCat = Object.values(categoriesMap);
var catArray = valCat.map((item) => {
return [last_id, item];
});
let sql = `BEGIN; INSERT INTO entries (title,kindof) VALUES("${[
req.body.title,
]}","${req.body.kindof}");
INSERT INTO categories_main (entry_id, cat_id) VALUES ? ;
COMMIT;`;
// array as second query parameter
let query = connection.query(sql, [catArray], (err,results) => {
if (err) throw err;
});
})
.catch(console.log);
i need to run a first query that i get from it a list of auctions, i need to run a second query that for each auction i get the lowest bid for this auction.
after i get the results i need to push the lowest bid to the auctions json that i recive from the first query (results1) in for loop.
when i console log results i get a array with 9 object (it should be 3) and the lowest bid property is only exists on 3 of them objects, it might be better way of doing this.
the console.log of results after adding it the lowest bids :
https://imgur.com/a/eiYcycZ
router.get('/get-live-auctions', auth, (req, res) => {
try {
const userID = req.userData.userID;
db.query(`SELECT auctions.UID,auctions.OriginCompany,auctions.DestinationCompany,auctions.OriginAddress,auctions.DestinationAddress,auctions.PickupDate,auctions.TotalWeight,auctions.StartDate,auctions.BidEndDate,auctions.AuctionEndDate,auctions.AuctionState,auctions.AuctionSerialNumber
From auctions
WHERE UserId='${userID}' AND AuctionState = 2 OR AuctionState = 3 OR AuctionState = 4`, (
err, results, fields) => {
for (let i = 0; i < results.length; i++) {
let auctionsIDS = results[i].UID;
db.query(`SELECT MIN(TotalPrice) AS lowestBid
FROM bids
Where AuctionID = '${auctionsIDS}'
`, (err2, results2, fields2) => {
let lowestBid = results2[0].lowestBid;
results.lowestBid = lowestBid;
console.log(results);
if (err2) return res.send(error);
}
)
}
res.status(200).json(results);
});
} catch (error) {
return res.status(500).send("Server error");
}
})
how to solve this issue?
I run via two for-loops through a MySQL table "Book" to get the values:
If I use explicitly the column name "Betrag" to get the value (e.g. res[i].Betrag ), it works! When I use for the column name a variable ('colName'), it issues an error message.
How can I get the values of a MySQL table without typing the column name in the code?
Thanks for your help,
M#trix
Value.toString()
app.get('/', function (req, res) {
//Build connection to MySQL database
var mysql2 = require('mysql');
var db2 = mysql2.createPool({
host: "127.0.0.1",
user: "...",
password: "...",
database: "DataRobot"
});
db2.query('SELECT * FROM Book', function (error, results, fields) {
if (error) throw error;
});
function setResHtml(sql, cb){
db2.getConnection((err, con)=>{
if(err) throw err;
con.query(sql, (err, res, cols)=>{
if(err) throw err;
for(var i=0; i<res.length; i++){
for(var j=0; j<3; j++) {
var colName= cols[j].name;
console.log("res[i].Betrag:");
console.log(res[i].Betrag); // shows the value
console.log("res[i].colName:");
console.log(res[i].colName); // shows an error message!!!!
};
}
con.release();
return cb(table);
});
});
}
Get entries via a variable for the column name.
#Stock Overflaw: You are absolutely right. I tried res[i][Betrag]; that did not work. However, res[i][colName] works! Thank you very much!
As a summary:
You get a single entry of an array with variable (e.g. colName):
res[i][colName]
You get a single entry of an array without variable (e.g. "Betrag"):
res[i].Betrag
First of all, I have to tell you I'm pretty noob in this "universe". I'm using: ExpressJs, MySql, Body-Parser, Express-session, Ejs template for creating an Basic Contacts Application in Node.
My database is composed from 3 tables:
user (user_id, first, second name, username, password)
contacts (ct_id, first, second name, phone numb.)
user_contacts (user_id, ct_id) --> foreign keys for user and contacts
I want to listing on /myProfile page all details about user and his contacts.
I don't know how to handle the select queries.
So, after some documentation I did this:
conn.query('SELECT * FROM user_contacts WHERE user_id= ?', req.session.user_id, function (err, result) {
if(err) throw err;
console.log(result);
var queryArray = "";
for(var i = 0; i < result.length; i++){
queryArray += `SELECT * FROM contacts WHERE ct_id= ${result[i].ct_id}; `;
}
console.log(queryArray);
conn.query(queryArray, function (err, result) {
if(err) throw err;
console.log(result);
res.render('myProfile/contacts', {
title: `${req.session.user_nickname}'s Contacts`,
data: result
});
});
});
But I have an error
ER_PARSE_ERROR: You have an error in your SQL syntax;
..when queryArray.length > 1
I searched and it's something about Multiple statement queries but I dont know how to solve it.
Edit 2:
I modify my code..
conn.query('SELECT * FROM user_contacts WHERE user_id= ?', req.session.user_id, function (err, result) {
if(err) throw err;
var datas = [];
for(var i = 0; i < result.length; i++){
getContacts = function(query){
conn.query(query, function (err, result) {
console.log('Creating data');
data = {
user: req.session.user_nickname,
contact:{
ct_firstName: result[0].ct_firstName,
ct_SecondName: result[0].ct_SecondName,
ct_PhoneNumber: result[0].ct_PhoneNumber
}
}
return data;
});
}
console.log('Send data to array');
datas.push(getContacts(`SELECT * FROM contacts WHERE ct_id = ${result[i].ct_id}`));
}
console.log(datas); // [ undefined, undefined ]
res.render('myProfile/contacts',{
title: `${req.session.user_nickname}'s profile`,
data: datas
})
});
But now my array contain undefined objects?? Any solution?
Maybe is something about scope?
My result:
Send data to array
Send data to array
[ undefined, undefined ]
Creating data
Creating data
I push the object to array before creating it. How is it possible?
1797,
I noticed you have several small queries grabbing the contact info for a given user. You could simplify your code by combining your queries into a single one. Often times 1 big query is more efficient (plus it's easier to maintain). I'm using a join. More info here.
const contacts = [];
const query = "
SELECT c.*
FROM user_contact uc
JOIN contact c ON uc.contact_id = c.contact_id
WHERE uc.user_id = ?
GROUP BY c.contact_id
";
conn.query(query, req.session.user_id, (err, results) => {
if (err) throw new Error(err);
// it seems that this could just be 'contacts = results' since they
// have the same structure
contacts = results.map(result => {
return {
ct_firstName: result[0].ct_firstName,
ct_SecondName: result[0].ct_SecondName,
ct_PhoneNumber: result[0].ct_PhoneNumber
};
});
res.render('myProfile/contacts',{
title: `${req.session.user_nickname}'s profile`,
data: contacts
});
});
I am inserting multiple rows in the MySql database table the first row is getting inserted but for remaining it is showing the error:
[Error: ER_DUP_ENTRY: Duplicate entry '2' for key 'PRIMARY']
code: 'ER_DUP_ENTRY',
errno: 1062,
sqlState: '23000',
index: 1,
This is the structure of id field:
If I insert a single row the auto-increment works file.
I am not able to rectify the problem. Please help. Thanks.
EDIT
I am using node-rom2 and the code is
modelObj.create(arrayOfObjects, function (err, result) {
if (err) {
console.log("The error is :", err);
}
else {
response.status = 'success';
response.data = result;
}
next(response);
});
The SQL query is generated dynamically.
Now I got the solution, the mistake I was doing is I was generating the data using a for loop like this:
var data = { name:'john', age:24, email:'abc#abcd.com'};
var arrayOfObjects= [];
for (var i = 0; i < 4; i++){
arrayOfObjects.push(data);
}
modelObj.create(arrayOfObjects, function (err, result) {
if (err) {
console.log("The error is :", err);
}
else {
response.status = 'success';
response.data = result;
}
next(response);
});
So each and every record is same in this condition. However other than id none column having the property primary-key. I think it can be the behavior of the database or the node-orm2 can also be the reason, so it is not accepting the exact same values.
In actual, all the record won't be same. If you have some other point please let me know your thoughts. Thanks.