Sometimes, we want to retrieve the last inserted ID with Node.js MySQL.
In this article, we’ll look at how to retrieve the last inserted ID with Node.js MySQL.
How to retrieve the last inserted ID with Node.js MySQL?
To retrieve the last inserted ID with Node.js MySQL, we can get it from the callback that’s called when the query is done.
For instance, we write
connection.query('INSERT INTO posts SET ?', {
title: 'test'
}, (err, result, fields) => {
if (err) {
throw err;
}
console.log(result.insertId);
});
to call connection.query
to make a INSERT query.
We call query
with a callback and get the ID of the inserted entry with result.insertId
.
Conclusion
To retrieve the last inserted ID with Node.js MySQL, we can get it from the callback that’s called when the query is done.