Search code examples
node.jsexpressnode-postgres

How to check for node-postgres if no results


I am confused what exactly node-postgres postgres database returned if no records ?

try {
  const {
    rows: [user]
  } = await pool.query(`SELECT * FROM "users" WHERE username = $1 LIMIT 1`, [
    username
  ]);

  console.log('user', user);

  if (!user || typeof username !== 'undefined') return false;

  return await bcrypt.compare(password, user.password);
} catch (e) {
  console.log(e);
}

How to check if there is no user result


Solution

  • For a SELECT query, the pg.Result rows is an empty array [] with rows.length === 0

    The rowCount === 0 as well but this can be different in an INSERT/UPDATE query where it becomes the updated rows.