node.js - pg.connect 不是一个函数?

标签 node.js heroku pg

似乎有很多文档(例如 https://devcenter.heroku.com/articles/heroku-postgresql#connecting-in-node-js,但也包括本网站在内的其他地方)表明与 pg.js Node 包连接的正确方法是使用 pg.connect。但是,我尝试(在我的实际代码出现之前的问题之后)使用上述 Heroku 文档中显示的确切代码进行测试:

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));
    });
});

我收到错误消息“pg.connect 不是函数”。发生了什么,我该如何解决?

最佳答案

pg 的新版本,即 7.0.0,大约在 15 小时前发布(从我写这篇文章开始)。

这个版本有很多变化,其中之一是 pg.connect 已被硬弃用(换句话说:删除)以支持 pg.Pool(... ).connect(...),如此处所述:https://node-postgres.com/guides/upgrading

新的连接方式如下:

var pool = new pg.Pool()

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

// pool shutdown
pool.end()

许多旧文档不会反射(reflect)这些更改,因此他们使用的示例代码将不再适用。

您可以尝试重写示例代码以使其在 7.0.0 中运行,或者显式安装仍可与示例代码一起使用的旧版本:

npm install pg@6

关于node.js - pg.connect 不是一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45174120/

相关文章:

django - 错误: Cannot find module 'socket.io/node_modules/redis'

css - ReactJS + Heroku : Why doesn't my website become mobile responsive?

node.js - PostgreSQL 错误 : relation does not exist on INSERT Statement

javascript - 如何使用 PG 在 Node JS 中获取 client.query 的值?

javascript - 变量声明的 Mac 终端 Node REPL 输出

ios - 通过 Node.js 服务器后端连接两个 iOS 设备

node.js - 无法从 MERN 应用程序的后端在浏览器中接收/设置 cookie,后端托管在 heroku 上,前端托管在 netlify 上

node.js - 在 Heroku 中通过 Node 连接到 Redis 数据库

ruby-on-rails - Heroku 上的 Postgresql 全文搜索

c - rails install pg - 找不到“libpq-fe.h header ”