Search code examples
node.jstypescriptmysql2

How to make execute/query in mysql2 return array instead of mysql.QueryResult


I've written this test query:

      const [results] = await connection.execute(
        `
          SELECT * FROM providers WHERE id IN (${ids.join(',')})
        `,
      );

However it returns mysql.QueryResult. And given that this array may contain thousands of records, I don't want to do this ridiculous JSON.parse(JSON.stringify(results)).


Solution

  • Destructure the result of the operation using:

    import { RowDataPacket } from 'mysql2/promise';
    
    interface Provider extends RowDataPacket {
        id: number;
        // Other Provider properties
    }
    
    const [providers] = await connection.execute<Provider[]>(`SELECT * FROM providers WHERE id IN (${ids.join(',')})`);
    

    After this, providers is array and contains the result of the query execution. You can iterate over the values of an array:

    for (const provider of providers) {
        console.log(provider.id);
        // your code here
    }