Search code examples
node.jsexpressmysqljs

insertId returning 0 after posting with mysqljs and stored procedure


Using mysqljs to query mySQL database via a stored procedure for a webAPI endpoint in express.js. I am required to return the inserted object. for this, I tried to acess the insrtedId based on the documentation from mysqljs. but the insertedid always returns zero.

I tried to include the output parameter in the stored procedure and set it to LAST_INSERT_ID(). Still insertedId is 0

router.post("/", (req, res) => {
  name = req.body.name;
  apiconnection.query(
    `CALL userAdd ('${name}', @_LID)`,
    (error, rows, fields) => {
      if (error) {
        res.json({ message: `cant be saved to the database` });
      } else {
        const id = rows.insertId;
        router.get("/", (req, res) => {
          apiconnection.query(
            `select * from tbl1 where id = ${id}`,
            (error, rows, fields) => {
              if (!error) {
                res.json(rows);
              } else {
                res.json(error);
              }
            }
          );
        });
       }
    }
  );
});

here is the stored procedure 

```CREATE DEFINER=`root`@`localhost` PROCEDURE `userAdd`(IN _name varchar(250), OUT _LID int)
BEGIN
  insert into tbl1(name) values (_name);
  set _LID = LAST_INSERT_ID();
END```

note that the id is set to auto increment

Solution

  • As I am requrired to work with only stored procedures, I selected the added record in the insert stored procedure. This makes that record available when the POST method is called.

    CREATE DEFINER=`root`@`localhost` PROCEDURE `userAdd`(IN _name varchar(250), OUT _LID int)
    BEGIN
      insert into tbl1(name) values (_name);
      set _LID = LAST_INSERT_ID();
      select * from tbl1 where id = _LID;
    END
    

    then in the POST method, the added recored can be accessed as an object from the rows as 'rows[0][0]' . no need to make a get call to the database

       router.post("/", (req, res) => {
      name = req.body.name;
      apiconnection.query(
        `CALL userAdd ('${name}', @_LID)`,
        (error, rows, fields) => {
          if (error) {
            res.json({ message: `cant be saved to the database` });
          } else {
            res.json(rows[0][0]);
          }
        }
      );
    });