Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pg.connect not a function?

Tags:

node.js

heroku

pg

There appears to be a lot of documentation (e.g. https://devcenter.heroku.com/articles/heroku-postgresql#connecting-in-node-js, but also elsewhere including this site) indicating that the proper method of connecting with the pg.js Node package is using pg.connect. However, I attempted (after previous problems with my actual code) to test by using the exact code shown on the aforementioned Heroku documentation:

var pg = require('pg');

pg.defaults.ssl = true;
pg.connect(process.env.DATABASE_URL, function(err, client) {
  if (err) throw err;
  console.log('Connected to postgres! Getting schemas...');

  client
    .query('SELECT table_schema,table_name FROM information_schema.tables;')
    .on('row', function(row) {
      console.log(JSON.stringify(row));
    });
});

And I got the error message "pg.connect is not a function". What is going on, and how do I fix it?

like image 592
user1837296 Avatar asked Jul 18 '17 18:07

user1837296


1 Answers

A new version of pg, namely 7.0.0, was published about 15 hours ago (from the time I'm writing this).

This version has lots of changes, one of them being that pg.connect has been hard-deprecated (in other words: removed) in favor of pg.Pool(...).connect(...), as documented here: https://node-postgres.com/guides/upgrading

The new method of connecting looks like this:

var pool = new pg.Pool()

// connection using created pool
pool.connect(function(err, client, done) {
  client.query(/* etc, etc */)
  done()
})

// pool shutdown
pool.end()

Lots of older documentation will not reflect these changes, so the example code they use won't work anymore.

You can either try and rewrite the example code so it works in 7.0.0, or explicitly install an older version that will still work with the example code:

npm install pg@6
like image 159
robertklep Avatar answered Nov 05 '22 06:11

robertklep