query.on不是一个函数 [英] query.on is not a function
问题描述
我正在尝试学习如何使用javascript连接到postgresql数据库但是当我尝试使用query.on(...)将查询记录到控制台时,我收到一个类型错误,上面写着query.on不是一个功能。我已经广泛搜索了如何解决这个问题,但似乎无法找到关于.on函数的任何文档。我知道连接成功,因为当我从终端查询数据库时,已经添加了两个新行。
I am trying to learn how to use javascript to connect to a postgresql database but when I try to log a query to the console using query.on(...), I get a type error that says "query.on is not a function". I have searched extensively on how to resolve this but can't seem to find any documentation on the .on function. I know that the connection is successful because when I query the db from terminal, the two new rows have been added.
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();
});
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中删除。
query.on
has been removed from node-pg 7.
参见 https://node-postgres.com/guides/upgrading 了解如何正确处理行。
See https://node-postgres.com/guides/upgrading for how to properly handle rows.
通常的方法是使用promises或async / await(以更清晰的方式使用promises):
The usual way is to use promises or async/await (using promises in a clearer way):
await client.connect();
var res = await client.query("SELECT * FROM json_test");
res.rows.forEach(row=>{
console.log(row);
});
await client.end();
这篇关于query.on不是一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!