query.on不是一个函数

tvo*_*k13 14 javascript node.js node-postgres postgresql-9.6

我正在尝试学习如何使用javascript连接到postgresql数据库但是当我尝试使用query.on(...)将查询记录到控制台时,我得到一个类型错误,上面写着"query.on不是功能".我已经广泛搜索了如何解决这个问题,但似乎无法找到关于.on函数的任何文档.我知道连接成功,因为当我从终端查询数据库时,添加了两个新行.

jsontest.js

var pg = require('pg');
var conString = "postgres://[username]:[password]@localhost:5432/VONKTA1";
//username and password masked

var client = new pg.Client(conString);

client.connect();

client.query("INSERT INTO json_test (name, attributes) VALUES ('Ted', $1)", [{"age": 2, "gender": "M"}]);
client.query("INSERT INTO json_test (name, attributes) VALUES ('Sarah', $1)", [{"age": 8, "gender": "F"}]);

console.log("about to query");

var query = client.query("SELECT * FROM json_test");

query.on('row', function(row) {
    console.log(row);
});

query.on('end', function() {
    client.end();
});
Run Code Online (Sandbox Code Playgroud)

的package.json

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "test.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "pg": "^7.0.2",
  }
}
Run Code Online (Sandbox Code Playgroud)

Den*_*ret 17

query.on 已从node-pg 7中删除.

有关如何正确处理行的信息,请参阅https://node-postgres.com/guides/upgrading.

通常的方法是使用promises或async/await(以更清晰的方式使用promises):

await client.connect();
var res = await client.query("SELECT * FROM json_test");
res.rows.forEach(row=>{
    console.log(row);
});
await client.end();
Run Code Online (Sandbox Code Playgroud)

  • 注意,你不能在`async`函数之外使用关键字`await`.将代码放在函数内,并使用`async`作为前缀"function". (5认同)

小智 5

这对我来说是这样的:

var pg = require("pg");

var connectionString = {
  user: 'user',
  host: 'host',
  database: 'db',
  password: 'pass',
  port: 5432,
};

var pool = new pg.Pool(connectionString);

pool.connect(function(err, client, done) {

    const query = client.query(new pg.Query("SELECT * from products"))
    query.on('row', (row) => {
        console.log(row);
    })
    query.on('end', (res) => {
        // pool shutdown
        console.log("ending");
        pool.end()
    })
    query.on('error', (res) => {
        console.log(res);
    })

    done()
})
Run Code Online (Sandbox Code Playgroud)

来源:https : //node-postgres.com/features/connecting