Search code examples
mysqlnode.jsnode-mysql2

NodeJS mysql query returning wrong result


I'm getting [ { 'AVG(Price)': '31000.0000' } ] instead of '31000.0000

this is the function

async function getAveragePrice(year) {
const sql = await init();
const [rows] = await sql.query('SELECT AVG(Price) FROM Car where year= 
?', [year], (err, result) => {
  if (err) {
     return null;
  }
 });
 return rows;
}

I'm using nodejs mysql2


Solution

    1. the callback part is redundant
    2. this is expected behavior, .query(sql) returns Promise<array of rows> and row is the object where each key is the corresponding field name
    async function getAveragePrice(year) {
      const db = await init();
      const [rows] = await db.query('SELECT AVG(Price) as avg FROM Car where year=?', [year])
      return rows[0].avg;
    }