Pg.connect is not a function?

There seems 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 correct way connections with pg.js Node package is used by pg.connect. However, I tried (after previous problems with my actual code) to test using the exact code shown in the above 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 happening and how to fix it?

+7
heroku pg
source share
2 answers

The new version of pg , namely 7.0.0, was published about 15 hours ago (since the writing of this article).

There are many changes in this version, one of which is that pg.connect was deprecated (in other words: removed) in favor of pg.Pool(...).connect(...) , as described here: https: / /node-postgres.com/guides/upgrading

The new connection method is as follows:

 var pool = new pg.Pool() // connection using created pool pool.connect(function(err, client, done) { client.query(/* etc, etc */) done() }) // pool shutdown pool.end() 

Many old documents do not reflect these changes, so the sample code that they use will no longer work.

You can either try or rewrite the example code to work in 7.0.0, or explicitly install an older version that will work with sample code:

 npm install pg@6 
+18
source share

pg : postgresql => ( https://www.npmjs.com/package/pg )

pg.connect deprecated since version 6.3 ❌

Instead, there is another method called pool

Here's how to easily configure node-postgres using express .

 const pg = require('pg'); const express = require('express'); const app = express(); const config = { user: 'postgres', database: 'YOURDBNAME', password: 'YOURPASSWORD', port: 5432 }; // pool takes the object above -config- as parameter const pool = new pg.Pool(config); app.get('/', (req, res, next) => { pool.connect(function (err, client, done) { if (err) { console.log("Can not connect to the DB" + err); } client.query('SELECT * FROM GetAllStudent()', function (err, result) { done(); if (err) { console.log(err); res.status(400).send(err); } res.status(200).send(result.rows); }) }) }); app.listen(4000, function () { console.log('Server is running.. on Port 4000'); }); 

For more information, see http://www.javascriptpoint.com/nodejs-postgresql-tutorial-example/

+1
source share

All Articles