Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

164
Views
Express.js : get inserted Id with nested queries

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
            });
        });

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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
                });

            }
        })
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!