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?



所有评论(0)