0

When I try to run then function on it, it will return this error

TypeError: Cannot read properties of undefined (reading 'then')
at Object.\<anonymous\> (/app/src/index.js:52:2)
at Module.\_compile (node:internal/modules/cjs/loader:1546:14)
at Module.\_extensions..js (node:internal/modules/cjs/loader:1691:10)
at Module.load (node:internal/modules/cjs/loader:1317:32)
at Module.\_load (node:internal/modules/cjs/loader:1127:12)
^
const { Client } = require('pg');

const PG_USER = 'root';
const PG_PASSWORD = 'example';
const PG_HOST = 'postgres';
const PG_PORT = '5432';
const PG_URI = `postgresql://${PG_USER}:${PG_PASSWORD}@${PG_HOST}:${PG_PORT}`;

const client =  new Client({
  connectionString: PG_URI,
});

client.connect(PG_URI)
  .then( () =>console.log('connect to postgresdb...'))
  .catch((err)=>console.log('failed connect to postgresdb:' ,err))                                                                                                            
2
  • version: 10.8.1 Commented Aug 24, 2024 at 7:44
  • "pg": "^8.12.0" Commented Aug 24, 2024 at 8:46

1 Answer 1

2

I think you need to remove PG_URI from your client.connect method call. You've already provided PG_URI when you instantiated Client. As far as I can tell, client.connect doesn't take any arguments and is used just to initiate the connection to your database.

Edit: Per the comment below, you can pass a callback but then it doesn’t return a promise.

Sign up to request clarification or add additional context in comments.

6 Comments

pg.connect can take an argument ... a callback ... and if an argument is supplied, it doesn't return a Promise - which explains the error perfectly, since presumably it returns undefined when an argument is present, and undefined famously has no .then method
@mhborthwick if i remove PG-URI from client.connect call , it change the error to failed connect to postgresdb: Error: connect EHOSTUNREACH 172.18.0.2:5432 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1605:16) { errno: -113, code: 'EHOSTUNREACH', syscall: 'connect', address: '172.18.0.2', port: 5432 }
@Jaromanda , so what should i do ?
@mohamedmoniem EXACTLY what this answer tells you to do ¯\_(ツ)_/¯
Thanks @Jaromanda - edited my answer per your comment.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.