Where to place the Commit block of a complex NodeJS MySQL Transaction? - javascript

I have the following code in NodeJS which works well to;
Begin a MySQL transaction;
Create an audiopost;
Update an audiopost.
Check to see if tag1 exists and if not, create it and insert into a tag table. If it does exist simply insert it to the tag table.
Commit the transaction;
But now I'd like to also check for tag2 and tag3 also.
Unfortunately, I can't figure out where and how to place the commit block
in order to keep it all as a single transaction.
If I put it just before the closing of the check for "tag1" the code won't get as far as "tag2" and "tag3". But if I put it after then the closing brackets to the connection queries are in the wrong place. Here's the code;
var mysql = require("mysql");
var express = require("express");
var connection = require("../database");
var createAudiopost = function(req, res, next){
var title = req.body.title;
var userid = req.body.userid;
var opid = req.body.opid;
var tag1 = req.body.tag1;
var tag2 = req.body.tag2;
var tag3 = req.body.tag3;
connection.beginTransaction(function(err) {
if (err) { throw err; }
connection.query('INSERT INTO ?? (title,userid,opid) VALUES (?, ?, ? )', ['audioposts',title,userid,opid], function(err, result) {
if (err) {
connection.rollback(function() {
throw err;
});
}
var audioname = userid + '-' + result.insertId + '.m4a';
var newid = result.insertId;
console.log("newid: " , newid );
connection.query('UPDATE ?? SET audioname=? WHERE audioid = ?', ['audioposts',audioname,newid], function (error, result, fields) {
if (err) {
connection.rollback(function() {
throw err;
});
}
if (tag1) {
connection.query('SELECT tagid FROM tags WHERE tagname = ?', [tag1], function (error, result, fields) {
if (err) {
connection.rollback(function() {
throw err;
});
}
const tagid1 = result[0].tagid;
if (result < 1) {
connection.query('INSERT INTO tags SET tagname = ?', [tag1], function (error, result, fields) {
if (err) {
connection.rollback(function() {
throw err;
});
}
console.log("lets see this ridiculous result", result);
const tagInsertId = result.insertId;
connection.query("INSERT INTO entitytag SET audioid = ?, tagid = ?, userid = ?", [newid, tagInsertId, userid], function (error, result, fields) {
if (err) {
connection.rollback(function() {
throw err;
});
}
connection.commit(function(err) {
if (err) {
connection.rollback(function() {
throw err;
});
}
console.log('success!');
newid = result.insertId;
res.json({
"title" : title,
"userid" : userid,
"opid" : opid,
"insertid": newid
}); //resjson success
}); //commit
}); // insert entitytags
}); // insert tags
} // if row
else {
connection.query("INSERT INTO entitytag SET audioid = ?, tagid = ?, userid = ?", [newid, tagid1, userid], function (error, result, fields) {
if (err) {
connection.rollback(function() {
throw err;
}); //err
} //err
connection.commit(function(err) {
if (err) {
connection.rollback(function() {
throw err;
});
}
console.log('success!');
res.json({
"title" : title,
"userid" : userid,
"opid" : opid,
"insertid": newid,
"tag1": tag1
}); //resjson success
}); //commit
}) // insert entitytag2
}
}); //select tagid
}//tag1
}); //update
}); //insert
}); //begin transaction
} //createaudiopost
module.exports = createAudiopost;
Any suggestions for how I can complete such a complex transaction? I basically need to repeat the entire section of if (tag1) for tag2 and tag3.

Related

Variable inaccessible inside callback function

I have a variable deleteFlag which is inaccessible inside a function even though the variable's scope is global.
Explanation (Pls refer my code simultaneously):
Here, I am trying to get a MongoDB collection details, the collection store a date document (result[i].date). The variable difResult stores the difference between the current date and the date fetched from MongoDB. And let's say if the value of difResult is more than a specific threshold then handle respective if-else conditions.
My if block i.e. if(difResult>20000) has a child-process, exec function and a callback function to delete MongoDB collection, now in this function I am trying to access var deleteFlag which is sort inaccessible.
Why? And how can I make is accessible inside my function?
app.js
MongoClient.connect("mongodb://localhost:27017/", {
useUnifiedTopology: true
}, function(err, db) {
if (err) throw err;
var dbo = db.db("dbName");
dbo.collection("colName").find({}).toArray(function(err, result) {
if (err) throw err;
for (var i = 0; i < result.length; i++) {
var difResult = Math.round((today - result[i].date));
var deleteFlag = result[i].date; // Declared here and should be accessbile within the function
console.log("Delete Flag " + deleteFlag.toISOString()); //Show correct value here
console.log("Result Date " + result[i].date);
if (difResult > 20000) {
var result2 = cp.exec("rm -rf /path/" + deleteFlag.toISOString(), function(error, stdout, stderr) {
if (error !== null) {
console.log('exec error: ' + error);
return res1.status(500).json({
error: "Failed!"
});
} else {
MongoClient.connect("mongodb://localhost:27017/", {
useUnifiedTopology: true
}, function(err, db) {
console.log("Delete Flag From Collection ", +deleteFlag.toISOString());
//The above console log gives NaN or null value
//Suggest that var deleteFlag is not accessible inside this callback function
if (err) throw err;
var dbo = db.db("dbName");
var myquery = {
date: deleteFlag
};
dbo.collection("colName").deleteOne(myquery, function(err, obj) {
if (err) throw err;
console.log("1 document deleted");
db.close();
});
});
}
});
} else {
console.log("Else msg");
}
}
db.close();
});
});
You don't have to call the database twice you can optimize your code and use it like this
MongoClient.connect("mongodb://localhost:27017/", {
useUnifiedTopology: true
}, function(err, db) {
if (err) throw err;
var dbo = db.db("dbName");
dbo.collection("colName").find({}).toArray(function(err, result) {
if (err) throw err;
for (var i = 0; i < result.length; i++) {
var difResult = Math.round((today - result[i].date));
var deleteFlag = result[i].date; // Declared here and should be accessbile within the function
console.log("Delete Flag " + deleteFlag.toISOString()); //Show correct value here
console.log("Result Date " + result[i].date);
if (difResult > 20000) {
var result2 = cp.exec("rm -rf /path/" + deleteFlag.toISOString(), function(error, stdout, stderr) {
if (error !== null) {
console.log('exec error: ' + error);
return res1.status(500).json({
error: "Failed!"
});
} else {
var myquery = {
date: deleteFlag
};
dbo.collection("colName").deleteOne(myquery, function(err, obj) {
if (err) throw err;
console.log("1 document deleted");
});
}
});
} else {
console.log("Else msg");
}
}
db.close();
});
});
However if for whatever reason you need to call the database twice then store deleteFlag values in an array and then access the array wherever you like

Node.js query INSERT callback not working as expected

Small problem when using POST and adding an INSERT. Works as below, but want to use a callball after the data has been inserted. At the moment the database is being updated. (good) but can't use the callback - I would expect this to be just below the throw error. So you could use result.insertId. Any thoughts welcome?
router.post('/group/:id', function(req, res) {
var idToken = req.params.id;
admin.auth().verifyIdToken(idToken).then(function(decodedToken) {
var userID = decodedToken.uid;
var name = encrypt(req.body.group);
getID(userID, function(result){
var ID = result;
var post = {ID:ID, name:name};
db.query('INSERT INTO cu_groups SET ?', post, function (error, results, fields) {
if (error)throw error;
//*** when I add response here get 502 bad gateway error.
});
res.sendStatus(200);
}); // depends on getID
// admin.auth cat
}).catch(function(error) {
res.sendStatus(error);
});
});
try this way :
router.post('/group/:id', function(req, res) {
var idToken = req.params.id;
admin.auth().verifyIdToken(idToken).then(function(decodedToken) {
var userID = decodedToken.uid;
var name = encrypt(req.body.group);
getID(userID, function(result){
var ID = result;
var post = {ID:ID, name:name};
db.query('INSERT INTO cu_groups SET ?', post, function (error, results, fields) {
if(error){
return res.status(500).send(error);
}
if(!error && results){
return res.status(200).send(results);
}
});
});
}).catch(function(error) {
return res.status(500).send(error);
});
});
if you want to use callback then ,create a separate function like :
var insertData = function(query,data,callback){
db.query(query, data, function (error, results, fields) {
if(error){callback(error,null);}
if(!error && results){callback(null,results);}
});
});
and call this way inside getID :
getID(userID, function(result){
var ID = result;
var post = {ID:ID, name:name};
insertData('INSERT INTO cu_groups SET ?', post, function (error,data){
if(error){
return res.status(500).send(error);
}
if(data){
return res.status(200).send(data);
}
});
});
Working code below many thanks to Saurabh Mistry. I removed the SET post and added the table fields and values explicity.
router.post('/group/:id', function(req, res) {
var idToken = req.params.id;
admin.auth().verifyIdToken(idToken).then(function(decodedToken) {
var userID = decodedToken.uid;
var name = encrypt(req.body.group);
getID(userID, function(result){
var ID = result;
// query
let query = "INSERT INTO cu_groups (ID, name) VALUES('" + ID + "','" + name + "')";
// execute query
db.query(query, (error, result) => {
if(error){
return res.status(500).send(error);
}
if(!error && result ){
return res.send(result);
}
});
}); // depends on getID
// admin.auth cat
}).catch(function(error) {
return res.status(500).send(error);
});
});

stored procedure in node.js

im receiving an error when running this code
Error: ER_BAD_FIELD_ERROR: Unknown column 'employee_id' in 'field list'
the output is this
{ employee_id: '6',
employee_name: 'test',
employee_contact: 'test' }
this is my stored procedure code
CREATE DEFINER=`root`#`localhost` PROCEDURE `test3`(
in empid int(11) ,
in name1 varchar(45) ,
in contact varchar(45)
)
BEGIN
insert into test_table (employee_id , employee_name , employee_contact)
values (empid,name1,contact);
END
this is my index.js
router.post('/test', function (req, res, next) {
try {
var reqObj = req.body;
console.log(reqObj);
req.getConnection(function (err, conn) {
if (err) {
console.error('SQL Connection error: ', err);
return next(err);
} else {
// let employee_id = reqObj.employee_id
// let employee_name =reqObj.name1
// let employee_contact = reqObj.contact
var insertSql6 = "CAll test3(employee_id, employee_name, employee_contact)";
var insertValues6 = {
"employee_id": reqObj.empid,
"employee_name": reqObj.name1,
"employee_contact": reqObj.contact
};
var query = conn.query(insertSql6,insertValues6, function (err, result) {
if (err) {
console.error('SQL error: ', err);
return next(err);
}
console.log(result);
var test_Id = result.insertId;
res.json({
"test_id": test_Id
});
});
}
});
} catch (ex) {
console.error("Internal error:" + ex);
return next(ex);
}
});

Error: Cannot enqueue Query after invoking quit

when running the code below im having an Error: Cannot enqueue Query after invoking quit. i need to insert some data into two table .
can you help me to correct the code im really new here in node.js thank you so much.
Create Contact Service.
router.post('/contactinformationdetails', function (req, res, next) {
try {
var reqObj = req.body;
console.log(reqObj);
req.getConnection(function (err, conn) {
if (err) {
console.error('SQL Connection error: ', err);
return next(err);
} else {
var insertSql1 = "INSERT INTO contact_person SET ? ";
var insertValues1 = {
"site_name": reqObj.sitNam,
"first_name": reqObj.firName,
"last_name": reqObj.lastName,
"position": reqObj.posId,
"contact_number": reqObj.conNum,
"organization": reqObj.orga1,
"email_add": reqObj.emaAdd1,
};
var query = conn.query(insertSql1, insertValues1, function (err, result) {
if (err) {
console.error('SQL error: ', err);
return next(err);
}
console.log(result);
var Contact_Id = result.insertId;
res.json({
"Cont_id": Contact_Id
});
var insertSql5 = "INSERT INTO address_contactperson SET ? ";
var insertValues5 = {
"address_name": reqObj.addNam,
"address_one": reqObj.addOne,
"address_two": reqObj.addTwo,
"city": reqObj.city,
"province": reqObj.prov
};
var query1 = conn.query(insertSql5, insertValues5, function (err, result) {
if (err) {
console.error('SQL error: ', err);
return next(err);
}
console.log(result);
});
});
}
});
} catch (ex) {
console.error("Internal error:" + ex);
return next(ex);
}
});
You must try this with mongodb(MongoDB is an open-source document database and leading NoSQL database) the most easy and efficient way.
router.all('/todo/create', function (req, res) {
var taskcreate = req.Collection;
var task = req.body.task;
var date = req.body.date;
var status1 = req.body.status1;
var userid = req.body.userid;
var users = req.Collection;
var record = new taskcreate({
task: task,
date: date,
status1: status1,
userid: userid
});
if (task.length > 0) {
record.save(function (err, result) {
if (err) {
res.json({status: 0, message: err})
} else {
res.json({status: 1, userid: userid, task: task, date: date, message: " success"});
}
})
} else {
res.json({status: 0, msg: "Invalid Fields"});
}
});

Express.js ER_PARSE_ERROR when insert values

I want insert values in my database but i get a error "er_parse_error". I don't know where is the problem.
The code
var data = {};
function register(req,res,data) {
pool.getConnection(function (err, connection) {
if (err) {
res.json({"code": 100, "status": "Error"});
return;
}
var sql = "INSERT INTO table VALUES ?";
connection.query(sql, data, function (err, rows) {
if (!err) {
res.json(rows);
} else {
res.json(err.code);
}
})
});
router.route('/client/register')
.post(function(req,res) {
data = {
"usuer": req.query.user,
"password": req.query.password,
};
register(req, res, datos);
});

Categories