pg.connect不是一个函数?
问题描述:
似乎有很多文档(例如https://devcenter.heroku.com/articles/heroku-postgresql#connecting-in-node-js,但也包括此站点在内的其他地方)表明正确使用pg.js节点包进行连接的方法是使用pg.connect。不过,我试图(后与我的实际代码前面的问题)通过使用上述Heroku的文档上显示的确切的代码进行测试:pg.connect不是一个函数?
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()
许多较早的文档将不会反映这些变化,所以他们使用的示例代码将不再工作。
您可以尝试重写示例代码,以便它在7.0.0,或者明确地安装旧版本将仍与示例代码工作:
npm install [email protected]
答
pg
:在PostgreSQL =>(https://www.npmjs.com/package/pg因为版本)
pg.connect
已被弃用6.3❌
取而代之的被称为另一种方法pool
以下是如何使用express
轻松设置node-postgres
。
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');
});
请参考:http://www.javascriptpoint.com/nodejs-postgresql-tutorial-example/更多信息