Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get Last inserted id using Nodejs

I am working with Nodejs and i am using expressjs framework,Right now i am trying to get
"last inserted id" but i am getting "undefined" in console, How can i get last inserted id ? Here is my current code

static async addServiceDetail(salonId,serviceId,genderTypeId,price,serviceName)
    {
        const sql = `SELECT id from hc_servicesdetail WHERE shopId='${shopId}' AND  serviceId='${serviceId}' AND genderTypeId='genderTypeId'`;
        const [rows, fields] = await pool.execute(sql);
        if(rows<1)
            {
                const sql2 = `INSERT INTO hc_servicesdetail (shopId, serviceId, genderTypeId,price,serviceName) VALUES ("${shopId}", "${serviceId}", "${genderTypeId}", "${price}","${serviceName}")`;
                const datass = await pool.execute(sql2);
                console.log('last inserted id is ' +datass.insertId);
            }
        else
            {
                console.log('already exist');
            }   
    }
}

module.exports = User;

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Use the result.insertId property. This property is available in the callback function that gets executed when you perform an INSERT query.

static async addServiceDetail(shopId, serviceId, genderTypeId, price, serviceName) {
    const sql = `SELECT id from hc_servicesdetail WHERE shopId='\${shopId}' AND  serviceId='\${serviceId}' AND genderTypeId='\${genderTypeId}'`;
    const [rows, fields] = await pool.execute(sql);
    if (rows < 1) {
        const sql2 = `INSERT INTO hc_servicesdetail (shopId, serviceId, genderTypeId, price, serviceName) VALUES ("\${shopId}", "\${serviceId}", "\${genderTypeId}", "\${price}","\${serviceName}")`;
        const [datass, _] = await pool.execute(sql2);
        console.log('last inserted id is ' + datass.insertId);
    } else {
        console.log('already exist');
    }
}

Notice that I changed genderTypeId='genderTypeId' to genderTypeId='\${genderTypeId}' in the first SQL query. This should fix a syntax error.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading