I want to use the same pattern for destructuring query results, but seems I cannot. In the following code:
var {rows} = await client.query("SELECT id FROM mytable;");
var Id = rows[0].id; //destructured here as expected
if I then follow that with:
rows = await client.query('SELECT max(id) as id FROM table2;');
The only way I can access the value is like this:
rows.rows[0].id;
Shouldn't I be able to access as in the first instance, like this?
rows[0].id;
Do I need to somehow reset {rows}
?
Very new to JS so finding my way.
You still need to restructure the variable. Simply assign to rows
will just get the full response object assigned to the variable, as you've seen.
Destructuring to the same variable has a couple gotchas because you can't do this:
let {rows} = await client.query("SELECT id FROM mytable;");
// Error: unexpected token without declaration
{rows} = await client.query('SELECT max(id) as id FROM table2;');
// Error: Identifier 'rows' has already been declared
let {rows} = await client.query('SELECT max(id) as id FROM table2;');
You can declare var
multiple times:
var {rows} = await client.query("SELECT id FROM mytable;");
// no problemo
var {rows} = await client.query('SELECT max(id) as id FROM table2;');
If you want to declare with let
then you need to do something like:
let {rows} = await client.query("SELECT id FROM mytable;");
// this works too…
({rows} = await client.query('SELECT max(id) as id FROM table2;'));