I have developed a code in Node.js to execute insert queries using Promise.js but unfortunately, I am encountering an exception stating "Duplicate Primary Key" entry.
Here is the snippet of the code:
var Promise = require("promise");
var mySql = require("mysql");
var _ = require("underscore");
var connection = mySql.createConnection({
host : "localhost",
user : "root",
password : "rahul",
database : "testDb" //schema
});
connection.connect();
function insertDept(name){
return new Promise(fn);
function fn(resolve,reject){
getMaxDept().then(function(rows){
var deptId = rows[0]["DeptId"];
deptId = (_.isNull(deptId) === true) ? 125 : deptId;
var sql = "insert into departmentTbl values("+deptId+",'"+name+"')";
console.log(sql);
connection.query(sql,function(err,rows,fields){
if(err){
console.log(err);
return reject(err);
}else{
return resolve(rows);
}
});
}).catch(function(error){
return reject(error);
});
}//fn
}//insertDept
// More code follows
The issue arises when attempting to run multiple insert queries at once due to the parallel nature of promises. In this case, the primary key constraint for the second Department's insert query fails.
To address this problem, one approach would be to utilize triggers in the database to calculate the next value of the primary key (department ID) before inserting. Alternatively, adjustments could also be made within the Node.js code itself.