Search code examples
mysqlnode.jsbackendmysql2

How do I get the row inserted as a response from an INSERT INTO using mysql2 module?


I'm new using the mysql2 module and I'm trying to get from the result parameter of my INSERT INTO the data inserted back to use it after, the data I'm trying to get back is the ID assigned to that particular row.

const express = require('express');
const router = express.Router();

router.post('/devices', (req, res) => {

    let queryFirstTable = `INSERT INTO devicesdb.devices (token) VALUES ('${req.body.token}')`;
    pool.execute(queryFirstTable, (err, results, fields) => {
        if (err) throw err;
        console.log('hola' + results);
        res.send('Query executed')
    })
});


module.exports = router;

I'm getting back an array [object Object] and from what I've seen should be a String with the data inserted. This is what my console shows back.

[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
Running on port 3000.
hola[object Object]

What I want in return is the row I've I haven't been clear enough, don't know if it's possible.

enter image description here


Solution

  • Try console.log(results) instead of adding 'hola' at the front. You should be able to see what is inside the results object.