5

I have a very simple Knex query against a MySQL table to find the maximum value of the id column:

const maxId = await knex('some_table').max('id').first()

But this returns a TextRow object with a single, oddly named property. From a console.log:

TextRow { 'max(`id`)': 99 }

Is there an easy way for me to get the value, or do I have to use object property notation like this:

const idValue = maxId['max(`id`)']
AJ.
  • 16,368
  • 20
  • 95
  • 150
  • try this please https://stackoverflow.com/questions/48558183/knex-select-result-return-to-a-variable – nbk Jul 23 '19 at 21:55

1 Answers1

8

It appears the easiest answer is to alias the result, as in the second example shown here:

const maxIdQuery = await knex('some_table').max('id as maxId').first()
console.log(maxIdQuery.maxId)        // shows the value

Alternate syntax:

const maxIdQuery = await knex('some_table').max('id', { as: 'max_id' })
console.log(maxIdQuery[0]['max_id'])

Hope this helps someone in the future.

AJ.
  • 16,368
  • 20
  • 95
  • 150