0

In the code below the first query works as expected and the result is fine. But when the second query runs the result is undefined and it throws an error when trying to access the row value. I have run the actual query manually in the db and it returns a value so there is data.

    var cli = new pg.Client(conn);
    await cli.connect();

    //get last max log id
    const {rows} = await cli.query("SELECT value as id FROM public.mytable  where name = 'max_log_id'");
    lastMaxId = rows[0].id; //no error here
    console.log(lastMaxId);

    //get max log id
    const {res} = await cli.query('SELECT max(id) as id FROM public.myothertable');
    console.log('RES: ' + JSON.stringify(res)); //res = undefined
    maxId = res[0].id; //throws error here

Can I not run two queries with same client? Or do I need to reset the client somehow?

Thanks!

Kenobi
  • 465
  • 6
  • 13
  • In the second query you are destructuring the response with `{res}` instead of `{rows}`. This would depend on the return object form `cli.query` having a `res` property. Is that just a typo? – Mark Jul 23 '18 at 16:18
  • I cannot use const{rows} twice. Already declared in first query. But I have figured it out, answer posted below. – Kenobi Jul 23 '18 at 16:39

1 Answers1

0

Figured it out, here's the answer:

    var cli = new pg.Client(conn);
    await cli.connect();

    //get last max log id
    var {rows} = await cli.query("SELECT value as id FROM public.my table  where name = 'max_log_id'");
    lastMaxId = rows[0].id;
    console.log(lastMaxId);

    //get max log id
    rows = await cli.query('SELECT max(id) as id FROM public.myothertable');
    console.log('RES: ' + JSON.stringify(rows.rows[0].id));
    maxId = rows.rows[0].id;
Kenobi
  • 465
  • 6
  • 13