Answer a question

I am trying to use async await with mysql2 and pooling but I think I doing things wrong. Below is my code (as I said, I am not really sure if I am doing things right here).

    const pool = mysql.createPool({
      host: 'localhost',
      user: 'root',
      database: 'test',
      password: '',
      waitForConnections: true,
      connectionLimit: 10,
      queueLimit: 0
    });
    
    const promisePool = pool.promise();   // Get a Promise wrapped instance of that pool   
    

app.post('/api/register', (req, res) => {

    async function queryDB() {
    
        try {
          const addUser = await promisePool.execute(
            "INSERT INTO users (company, email, password) VALUES (?,?,?)",
            ['Ikea', 'Ikea@ikea.com', '123'],
          )
          const addAnother = await promisePool.execute(
            "INSERT INTO users (company, email, password) VALUES (?,?,?)",
            ['Google', 'Google@google.com', '123']
          )
    
          console.log(addUser)
          res.status(200).json('Users saved')
          
        } catch (err) {
          console.log(err)
          res.status(409).json('User already exist')
        };
      }
    
      queryDB();
})

The idea is that "addUser" should be saved, and if it is not unique, an error will occur (because the SQL database email column is set to unique) and then addAnother won't start inserting.

What I can't understand is how to get the insertId from the addUser insert? I will need it for the second insert. If I console.log addUser I can see an object like this:

ResultSetHeader {
  fieldCount: 0,
  affectedRows: 1,
  insertId: 72,
  info: '',
  serverStatus: 2,
  warn

So insertId is sent back to me, but I can't seem to reach it. If I try to grab it it says cant read property of undefined. I am feeling that I am doing this all wrong, so how should I do it instead to get the insertID?

Answers

It seems like the result was in an array. I solved it with: addUser[0].insertId. I never got LAST_INSERT_ID() to work though.

Logo

华为、百度、京东云现已入驻,来创建你的专属开发者社区吧!

更多推荐