node mysql2 can't access update results
Asked Answered
C

5

6

I'm doing a simple UPDATE with mysql2 :

   UPDATE table1
    SET table1.value1 = ?, table1.value2 = ? 
    WHERE user_id = (
      SELECT user_id 
      FROM user
      WHERE company_id = ?
    ) 

table1 is related to the user table by user_id, but I only have the company_id so I do a subquery (probably should be a join, but thats another discussion):

const [results, buff] = await connection.execute(query, values);
return results

However, when accessing the results to make sure there are no errors and that only a single row is updated, results returns:

  console.log
    ResultSetHeader {
      fieldCount: 0,
      affectedRows: 1,
      insertId: 0,
      info: 'Rows matched: 1  Changed: 0  Warnings: 0',
      serverStatus: 2,
      warningStatus: 0,
      changedRows: 0
    }

But I can't access the values. If I try results.affectedRows I get

Property 'affectedRows' does not exist on type 'RowDataPacket[] | RowDataPacket[][] | OkPacket | OkPacket[]'.

The only way to make it work is to do results['affectedRows']. Any suggestions?

Corson answered 2/6, 2020 at 15:49 Comment(2)
Have you seen this Git issue thread?Deferment
@PhaniMahesh I'm following their async/await suggestion: npmjs.com/package/mysql2#using-promise-wrapper The only way to get the error is with a try/catch, which I am using. Should I just rely on that for the success of the query?Corson
C
3

So I forgot to mention that this is a typescript error, and I was able to fix it by doing:

const [results, buff] = await connection.execute(query, values);
const json: any = results;
return json.affectedRows //or whatever property I want

This also works:

const [results, buff] = await connection.execute(query, values);
return json as any; //then in the calling fuction access the properties I want
Corson answered 3/6, 2020 at 3:10 Comment(4)
I also ended up making an interface for the mysql2 response, so I don't have to use anyCorson
could you please update your answer to show the interface you use? I'm stuck working against the RowDataPacket typeDemasculinize
So I'm doing const [results, buff] = await connection.execute(query, values); return results as IUpdateTokens, and the interface is interface IUpdateTokens { fieldCount?: number, affectedRows?: number, insertId?: number, info?: string, serverStatus?: number, warningStatus?: number, changedRows?: number, }Corson
okay interesting. I still think that would give my implementation trouble with the RowDataPacket... but I'll take a look soonDemasculinize
M
1

perhaps try in this way :

let result = await db.execute($sql, values);

result = JSON.parse(JSON.stringify(result));

console.log(result)

the output will be :

{
  fieldCount: 0,
  affectedRows: 1,
  insertId: 0,
  info: 'Rows matched: 1  Changed: 1  Warnings: 0',
  serverStatus: 2,
  warningStatus: 0,
  changedRows: 1
}

this way somehow makes it become a normal object to be accessed

so the object can be accessed like result.affectedRows, result.insertId, ...

Monied answered 27/6, 2023 at 17:36 Comment(0)
B
0

I recently faced the same problem and the solution I found is to add return type to connection.execute itself, from types provided by mysql2 const result = await pool.execute<OkPacket>(query, values); I reckon you no longer need it, but hopefully useful to someone else. Cheers.

Brittnee answered 22/3, 2023 at 14:47 Comment(0)
C
0

if ('affectedRows' in data && ... ) return data

Colima answered 25/5, 2024 at 13:4 Comment(0)
E
0
async function changePw(id: string, hash: string) {
    try {
        const [result] = await pool.execute('UPDATE User SET password_hash = ? WHERE id = ?',
            [
                hash,
                id
            ])
        const resObj = JSON.parse(JSON.stringify(result))
        if( resObj.affectedRows ) return 'success'
        else return 'fail'
    } catch (e) {
        console.log('userCalls.changePw error', e)
    }
}

https://sidorares.github.io/node-mysql2/docs/examples/queries/simple-queries/update#querysql

Ephesus answered 18/10, 2024 at 6:48 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.