I am trying to select data from my database table and then print it in the console. whenever I try the console returns undefined.
const sql = await pool.query("SELECT * FROM users");
for(rows in sql){
console.log(rows.username)
}
CodePudding user response:
Hey please know that query returns an array, so do this instead
const sql = await pool.query("SELECT * FROM users");
if(!sql.length) console.log("no data")
else{ for(let rows of sql){
console.log(rows.username)
}
}
CodePudding user response:
To get an array out of pool.query, you need to do the following:
const result = await pool.query("SELECT * FROM users");
const users = result.rows // get an array of users
If you want to get all the username from the users table, you can do:
const usernames = users.map((user) => user.username); // get an array of usernames