Search code examples
node.jspgpg-query

Node.js pg client query works for first query but fails for second query despite there being data


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!


Solution

  • 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;