Error in handling a post request (Express, MySql, Postman - mysql

When I'm trying to send a POST request using Postman, it gives me this error: "Cannot read properties of undefined (reading 'product_title')"
app.post("/product", async (req, res, next) => {
let product = {
product_title: req.body.product_title,
product_price: req.body.product_price,
product_type: req.body.product_type,
product_brand: req.body.product_brand,
};
let sql = `INSERT INTO products SET ?`;
await db.query(sql, product, (err, result) => {
if (err) {
throw err;
}
console.log(result);
});
res.send("Added");
});

use ? keyword
app.post("/product", async (req, res, next) => {
let product = {
product_title: req.body?.product_title,
product_price: req.body?.product_price,
product_type: req.body?.product_type,
product_brand: req.body?.product_brand,
};
let sql = `INSERT INTO products SET ?`;
await db.query(sql, product, (err, result) => {
if (err) {
throw err;
}
console.log(result);
});
res.send("Added");
});

Related

mySQL query in node.js is returning undefined

When making an sql query my function is returning undefined. I'm unsure how to fix this and was confused when I googled the problem. Here is a section of my code:
function randomfact() {
let sql = 'SELECT id FROM facts ORDER BY RAND() LIMIT 1;';
let query = db.query(sql, (err, result) => {
if (err) {
throw err;
}
else {
return result;
}
});
}
const app = express();
app.get("/", function(req, res) {
res.send(randomfact());
console.log(randomfact());
});
My best guess as to the issue is that I am returning an incorrect datatype but I am unsure on how to fix it.
Any advice is good advice thanks!
Change your randomfact function to return the query result:
function randomfact() {
let sql = 'SELECT id FROM facts ORDER BY RAND() LIMIT 1;';
return new Promise((resolve, reject) => {
db.query(sql, (err, result) => {
if (err) {
reject(err);
}
else {
resolve(result);
}
});
});
}
Wait for randomfact to return the result:
app.get("/", async function(req, res) {
const result = await randomfact();
res.send(result);
console.log(randomfact());
});

Calling mysql queries dependent on another query in node

can anyone help me.
I need to get result of queryA [which is an update query that returns ROW_COUNT( )], see if the result is equal to 1.
If not, just return it via res.json
If yes, call queryB [which returns a set of rows].
After which, I have to loop and call queryC to update each row. It has to be one at a time because the queryC is also inserting auditTrails within the stored procedure.
This is the source code:
exports.migrateCustomer = asyncHandler(async (req, res) => {
const { oldCustomerID, newCustomerID, userID } = req.body;
const connection = mysql.createConnection(config);
let sql = `CALL usp_UpdateCustomerCallStatusIdAndIsActive(?,?,?)`;
/*UPDATE Customer*/
const updateCus = connection.query(sql, [oldCustomerID, 'Duplicate', userID], (error, results, fields) => {
if (error) {
return console.error(error.message);
}
return results[0];
});
if (updateCus.rowCount == 1) {
let sql = `CALL usp_GetPurchaseOrderByCustomerIDAndNameSearch(?,?)`;
/*GET rows to be updated*/
const GetRows = connection.query(sql, [oldCustomerID, ''], (error, results, fields) => {
if (error) {
return console.error(error.message);
}
results[0].forEach(element => {
let sql = `CALL usp_UpdatePurchaseOrderByCustomerID(?,?)`;
/*UPDATE rows*/
connection.query(sql, [newCustomerID, userID], (error, results, fields) => {
if (error) {
return console.error(error.message);
}
});
});
});
}
res.json(updateCus);
connection.end();
});
Error:
TypeError: Converting circular structure to JSON
--> starting at object with constructor 'Query'
then another one at the bottom:
throw er; //Unhandled 'error' event
You are missing 'await' before the mysql.createConnection(config) and connection.query call, since these are asynchronous functions. Also in your code connection.end() should be inside the callback.
exports.migrateCustomer = asyncHandler(async (req, res) => {
const { oldCustomerID, newCustomerID, userID } = req.body;
const connection = await mysql.createConnection(config);
let sql = `CALL usp_UpdateCustomerCallStatusIdAndIsActive(?,?,?)`;
/*UPDATE Customer*/
const updateCus = await connection.query(sql, [oldCustomerID, 'Duplicate', userID], (error, results, fields) => {
if (error) {
connection.end();
return console.error(error.message);
}
return results[0];
});
if (updateCus.rowCount == 1) {
let sql = `CALL usp_GetPurchaseOrderByCustomerIDAndNameSearch(?,?)`;
/*UPDATE Customer*/
connection.query(sql, [oldCustomerID, ''], (error, results, fields) => {
if (error) {
connection.end();
return console.error(error.message);
}
results[0].forEach(element => {
let sql = `CALL usp_UpdatePurchaseOrderByCustomerID(?,?)`;
/*UPDATE Customer*/
connection.query(sql, [newCustomerID, userID], (error, results, fields) => {
connection.end();
if (error) {
return console.error(error.message);
}
});
});
});
}else{
connection.end();
return res.status(200).json({
customer:updateCus});
}
});

MySQL Node JS DELETE no working - 0 rows affected

I am trying to create a post route that will delete a user's data from several tables. I checked in mySQL workbench that the database user has this privilege. However when I click delete on the frontend, the queries appear to run but the rows do not get deleted. Can you someone please tell me where I am going wrong?
app.post('/disposal', redirectLogin, async(req, res) => {
const user = res.locals;
userStmt = `DELETE FROM users WHERE user_name ='${user.user_name}'`;
cashStmt = `DELETE FROM CASH WHERE user_name ='${user.user_name}'`;
tradesStmt = `DELETE FROM trades WHERE user_name ='${user.user_name}'`;
holdingsStmt = `DELETE FROM trades WHERE user_name ='${user.user_name}'`;
await connection.query(userStmt, (err, results) => {
if (err) throw err;
console.log(results);
connection.query(holdingsStmt, (err, results) => {
if (err) throw err;
console.log(results);
connection.query(cashStmt, (err, results) => {
if (err) throw err;
console.log(results);
});
connection.query(tradesStmt, (err, results) => {
if (err) throw err;
console.log(results);
});
});
});
req.session.destroy(err => {
if (err) {
return res.redirect("/dashboard");
}
res.clearCookie(SESS_NAME);
res.send("Ninja disposed!");
})
})
I needed to change user = res.locals to { user } = res.locals as it the former was coming back 'undefined' as it was not properly extracting.
You don't need to nest the calls if you are using async/await.
As the res.locals is an object which contains the user property, you have to get the user property.
You could get it by using Object destructuring syntax.
Try this.
app.post('/disposal', redirectLogin, async (req, res) => {
const { user } = res.locals;
userStmt = `DELETE FROM users WHERE user_name ='${user.user_name}'`;
cashStmt = `DELETE FROM CASH WHERE user_name ='${user.user_name}'`;
tradesStmt = `DELETE FROM trades WHERE user_name ='${user.user_name}'`;
holdingsStmt = `DELETE FROM trades WHERE user_name ='${user.user_name}'`;
try {
let results = await connection.query(userStmt);
console.log(results);
let holdinResult = await connection.query(holdingsStmt);
console.log(holdinResult);
let cashResult = await connection.query(cashStmt);
console.log(cashResult);
let tradesResult = await connection.query(tradesStmt);
console.log(tradesResult);
} catch (error) {
throw error
}
req.session.destroy(err => {
if (err) {
return res.redirect("/dashboard");
}
res.clearCookie(SESS_NAME);
res.send("Ninja disposed!");
})
})

Nodejs async/await for MySQL queries

I trying to execute 2 MySQL queries sequentially in Node.JS. MySQL queries work properly by itself.
I would like to do it with async/await function to be sure record is inserted before it's updated.
Here is the code:
router.post('/assign_new_item_id', async (req, res) => {
.....
try {
let qr1= "INSERT INTO foo1 ........;"
await pool.query( qr1, (err) => {
if (err) throw err;
});
let qr2= "UPDATE foo1 .....;"
await pool.query( qr2, (err) => {
if (err) throw err;
});
}catch(err){
console.log(err)
}
It seems that execution "hangs" within first await await block. What is the best way the ensure that both queries are executed consequently.
Thanks in advance for any help.
To await you need a Promise, Not Callback. In your case you are not returning a promise to await.
router.post('/assign_new_item_id', async (req, res) => {
// .....
try {
let qr1 = "INSERT INTO foo1 ........;"
await new Promise((res, rej) => {
pool.query(qr1, (err, row) => {
if (err) return rej(err);
res(row);
});
});
let qr2 = "UPDATE foo1 .....;"
await new Promise((res, rej) => {
pool.query(qr2, (err, row) => {
if (err) return rej(err);
res(row);
});
});
} catch (err) {
console.log(err)
}
});
Here I am promisifing the pool.query method and returning a promise.

Update whole or parts of column in a single row on MySQL and Nodejs

I am having trouble with querying whole or parts of the column in a single row.
I am creating a form that can both create (post) and edit(put) data into the form.
I managed to make the function post and delete work, but put(edit) always return a sql syntax error. The syntax works fine when simulating on phpmyadmin.
What is correct way of doing this? Thanks a lot.
exports.putProduct = router.put("/api/product/update/:id", (req, res) => {
const putData = req.body;
const idToPutData = req.params.id;
mySQL.query(
// "UPDATE `product` SET `category`=?, `productname`=?, `os`=?, `model`=?, `serialnumber`=?, `price`=?, `equipment_condition`=?, `detail`=?, `image`=? WHERE id=?", [putData, idToPutData],
"UPDATE `product` SET ? WHERE id=?", [putData, idToPutData],
(err, results, fields) => {
if (err) console.log(err);
}
);
});
exports.postProduct = router.post("/api/product/new", (req, res) => {
const postData = req.body;
mySQL.query(
"INSERT INTO `product` SET ?", postData,
(err, results, fields) => {
if (err) console.log(err);
res.end(JSON.stringify(results));
}
);
});
exports.deleteProduct = router.delete("/api/product/delete/:id", (req, res) => {
const conDeleteData = { id: req.params.id }
const idToDelete = req.params.id
mySQL.query(
"DELETE FROM `product` WHERE id=?", [idToDelete, conDeleteData],
(err, results, fields) => {
if (err) console.log(err);
res.end(JSON.stringify(results));
}
);
});
This is the correct way to perform a MySQL query update using Nodejs
exports.putProduct = router.put("/api/product/update/:id", (req, res) => {
const putData = req.body;
const idToPutData = req.params.id;
mySQL.query(
"UPDATE `product` SET `category`=?, `productname`=?, `os`=?, `model`=?, `serialnumber`=?, `price`=?, `equipment_condition`=?, `detail`=?, `image`=? WHERE id=?",
[putData.category, putData.productname, putData.os, putData.model, putData.serialnumber, putData.price, putData.equipment_condition, putData.detail, putData.image, idToPutData],
(err, results, fields) => {
if (err) console.log(err);
res.end(JSON.stringify(results));
}
);
});