Search code examples
javascriptnode.jspostgresqlnode-postgres

ReferenceError: users is not defined when trying to connect to postgres


i have been following this video https://www.youtube.com/watch?v=ufdHsFClAk0 and in 32:54 when the guy got the result i got an error ReferenceError: users is not defined. here is my code so far

const {Client} = require('pg')
const users = [{ id: 1 }] 
const client = new Client({
    user: "postgres",
    password: "testing",
    host: "BlackPearl",
    port: 5432,
    database: users
})

execute()

async function execute(){
    await client.connect()
    console.log("Connected")
    const results = await client.query("select * from users")
    console.table(results.rows)
    await client.end()
    console.log("Disconnected")
}

and here is what i see in pgAdmin4

that's my package.json

{
  "name": "expr",
  "version": "1.0.0",
  "description": "",
  "main": "experiment.js",
  "scripts": {
    "test": "node experiment.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "pg": "^8.7.1"
  }
}

in the terminal i write npm run test


Solution

  • change this:

    const client = new Client({
        user: "postgres",
        password: "testing",
        host: "BlackPearl",
        port: 5432,
        database: users
    })
    

    to this:

    const client = new Client({
        user: "postgres",
        password: "testing",
        host: "BlackPearl",
        port: 5432,
        database: 'users'
    })
    

    database name should be a string, not a reference, if it's called differently (not users) use the proper name