如何使用pg和Node.js正确查询Postgresql数据库?

时间:2019-01-14 18:23:26

标签: node.js postgresql express pg

我正在尝试使用Node,Express和pg模块查询Postgresql数据库。我收到错误“ TypeError:无法读取未定义的属性'查询'”

我已经查看了node-postgres模块网站的正确语法以及其他各种网站。我知道用于启用pg的语法在pg版本6.3.0之后已更改。

const express = require("express");
const path = require("path");
const bodyparser = require("body-parser");
const consolidate = require("consolidate");
const dust = require("dustjs-helpers");
const pg = require("pg");
var pool = new pg.Pool();


let app = express();

let connect = "postgres://postgres:secret@localhost:5432/my_database";

app.engine("dust", consolidate.dust);

app.set("view engine", "dust");
app.set("views", __dirname + "/views");

app.use(express.static(path.join(__dirname, "public")));

app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended: false}));

app.get("/", function(request, response, next) {
    pool.connect(function(err, client, done) {
      if (err) {
        console.log(`Not able to get a connection: ${err}.`);
        response.status(400).send(err);
      }
      client.query("SELECT * FROM recipes", function(err, result) {
        done();
      });
      pool.end();

    });
});

app.listen(3000, () => {
    console.log("Server running on port: 3000");
});

转到http://server_ip:3000应该显示一个网页,而不是节点因此错误而崩溃:

client.query("SELECT * FROM recipes", function(err, result) {
             ^
TypeError: Cannot read property 'query' of undefined

1 个答案:

答案 0 :(得分:0)

实例化连接字符串时,需要将其传递给池。

var pool = new pg.Pool({
    connectionString: 'postgres://postgres:secret@localhost:5432/my_database',
});