0

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

codingmonk
  • 33
  • 3

2 Answers2

0

Try this:

async function getAveragePrice(year) {
  const sql = await init()
  const row = await sql.query('SELECT AVG(Price) AS avg_price FROM Car where year=?', year, (err, result) => {
    if (err) {
      return null
    }
    return result.avg_price
  })
}
michelek
  • 2,380
  • 1
  • 13
  • 15
0
  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;
}
Marcello B.
  • 4,177
  • 11
  • 45
  • 65
Andrey Sidorov
  • 24,905
  • 4
  • 62
  • 75