query.on 不是函数

query.on is not a function

我正在尝试学习如何使用 javascript 连接到 postgresql 数据库,但是当我尝试使用 query.on(...) 将查询记录到控制台时,我得到了一个输入错误 "query.on is not a function"。我已广泛搜索如何解决此问题,但似乎找不到有关 .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', )", [{"age": 2, "gender": "M"}]);
client.query("INSERT INTO json_test (name, attributes) VALUES ('Sarah', )", [{"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();
});

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",
  }
}

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

这就是我的工作方式:

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

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

正如 Denys Séguret 在 Answer 中提到的,函数 query.on 已弃用。如果您是初学者并且想快速连接以尝试您的查询而不受 async/await 功能的困扰。您可以尝试以下代码:-

const { Pool, Client } = require('pg')
const connectionString = 'postgresql://dbuser:dbpassword@database.server.com:5432/mydb'

const pool = new Pool({
  connectionString: connectionString,
})

pool.query('SELECT NOW()', (err, res) => {
  console.log(err, res)
  pool.end()
})