Categories
JavaScript Answers

How to retrieve the last inserted ID with Node.js MySQL?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to retrieve the last inserted ID with Node.js MySQL?”

Leave a Reply

Your email address will not be published. Required fields are marked *