I have mysql nested queries in my express.js app and i need to get the inserted id of all queries but i got only insertId of the global query .. i got this error :
TypeError: Cannot read property 'insertId' of undefined
in line :
vid = results.insertId
my code :
let vid=""
con.query('INSERT INTO table1 SET ....', function(err, results, fields) {
let res1=results.insertId
con.query("insert into table2 ... res1='" res1 "'",
function(err0, results, fields) {
vid = results.insertId
if (err0) {
console.log( err0)
}
})
if (err) {
return res.status(500).json({
message: 'Error saving record',
err: err
});
}
return res.json({
message: 'saved',
id: results.insertId,
vid: vid
});
});
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You need to move the return res.json
into the "deepest" callback
let vid=""
con.query('INSERT INTO table1 SET ....', function(err, results, fields) {
let res1=results.insertId
con.query("insert into table2 ... res1='" res1 "'",
function(err0, results, fields) {
vid = results.insertId
if (err0) {
console.log( err0)
}
// ======= MOVED HERE ========
return res.json({
message: 'saved',
id: res1,
vid: vid
});
})
if (err) {
return res.status(500).json({
message: 'Error saving record',
err: err
});
}
})