I’m trying to connect my postgreSQL database to a node.js application but it keeps returning undefined whenever I try to log some of the data to the console using "node file_name".
I have a table called "users" and I want to log it’s columns as arrays to the console to make sure that my database is connected to the app currectly
I tried almost all the solutions on Stack overflow but none of them worked for me
const { Client } = require('pg')
const client = new Client({
host: 'localhost',
port: 5432,
database: 'postgres',
user: 'postgres',
password: '******'
})
client.connect()
client.query('SELECT * FROM users', (res, err)=> {
if (!err) {
console.log(res.rows)
} else {
console.log(err.message)
}
client.end()
})
2
Answers
From your code snippet, it appears that you are using the pg package to connect to your PostgreSQL database in your Node.js application. The issue you’re facing is that the result (res) is returning as undefined when you try to log the data to the console.
To fix this issue, you need to update your code slightly. The callback function for the client.query method accepts two arguments: err and result. However, in your code, you are using res instead of result, which is causing the undefined error.
Here’s the corrected code:
By updating the argument name from res to result in the callback function, you should be able to log the result.rows successfully without encountering the undefined error. Make sure that your PostgreSQL database is running and that the table "users" exists in the "postgres" database.
Just a suggestion: Rather than dumping your
users
table to verify the connection run the following:This will tell you exactly what you have connected to and the available path (schema list) in order searched and do so in 1 row returned. Your current verification query dumps the
users
table; if you 1000s of users you get 1000s of rows on the console.