Search code examples
node.jspostgresql

Why does my pool.query return "undefined"?


The first query returns rows:

(async () => {
  const {rows} = await pool.query('SELECT * FROM accounts');
  console.log(rows);
})();

This query returns "undefined":

(async () => {
  const {user} = await pool.query(`SELECT * FROM accounts WHERE username = '${req.body.username}'`);
  console.log(user);
})();

req.body.username is correct and the query should return 1 row. If I drop {} from user I do get a return, but with a list of field definitions i.e. const user not const {user}.

(async () => {
  const user = await pool.query(`SELECT * FROM accounts WHERE username = '${req.body.username}'`);
  console.log(user);
})();

Solution

  • Using const {rows} instead of const {user} everything is now behaving properly:

    (async () => {
      const {rows} = await pool.query(`SELECT * FROM accounts WHERE username = '${req.body.username}'`);
      console.log(rows);
    })();
    

    The other way of putting results into a variable:

    (async () => {
      const {rows: varName} = await pool.query(`SELECT * FROM accounts WHERE username = '${req.body.username}'`);
      console.log(varName);
    })();
    

    Using a Parameterized query:

    (async () => {
        const text = 'SELECT * FROM accounts WHERE username = $1';
        const values = [req.body.username];
        const {rows: varName} = await pool.query(text, values);
        console.log(varName);
    })();