2

I have a google cloud function using this code and it gives the error TypeError: pg.Pool is not a constructor at exports.postgresDemo I have

    {
  "dependencies": {
    "pg": "^2.0.5"
  }
}

as the dependencies. I don't know if the error is in node or cloud functions

Maxim
  • 4,075
  • 1
  • 14
  • 23
Andy Hay
  • 27
  • 1
  • 4
  • Please post that part of the snippet. Also, have you required pg? – SanSolo Dec 18 '18 at 04:30
  • @SanSolo what snippet? I copied Google's sample code and put in the info for my postgresql database and it gives me that error. Yes I required pg. Thanks for your help – Andy Hay Dec 19 '18 at 05:05
  • So the error is at this point? `pgPool = new pg.Pool(pgConfig)`? snippet because that's considered good practice instead of people having to go visit another page. Increases the chances of getting an answer – SanSolo Dec 19 '18 at 05:10
  • I just checked the [documentation](https://node-postgres.com/features/pooling) for the pg package. There the require is not a variable, it is : `const { Pool } = require('pg')` – SanSolo Dec 19 '18 at 05:17

2 Answers2

4

Should have been obvious from your dependencies :

"dependencies": {
    "pg": "^2.0.5"
  }
}

I ran this:

const pg = require('pg')
const pool = new pg.Pool()
console.log(pool)

and got the expected result. Difference is, in my dependencies, I have :"pg": "^7.7.1". The google example you are using also uses a more recent version of pg. I tried to install your version to double check using npm install pg@2.0.5 but got the error: npm ERR! notarget No matching version found for pg@2.0.5 So upgrade pg and it will work

SanSolo
  • 2,267
  • 2
  • 24
  • 32
0

For those who want or need to load the npm pg package as an ES6 module instead:

import pg from 'pg';
const { Pool } = pg;

const pool = new Pool({
  host: 'localhost',
  port: 5432,
  user: 'postgres',
  password: '********',
  database: 'postgres',
});

Related: Can I import the node-postgres module (pg) or is it CommonJS only?

swiss_knight
  • 5,787
  • 8
  • 50
  • 92