Query.on is not a function

I am trying to learn how to use javascript to connect to a postgresql database, but when I try to write a query to the console using query.on (...), I get a type error that says: "query.on is not a function" . I have searched many times how to resolve this, but cannot find any documentation for the .on function. I know the connection is successful, because when I request db from the terminal, two new lines are 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", } } 
+5
source share
1 answer

query.on been removed from node -pg 7.

See https://node-postgres.com/guides/upgrading for proper string handling.

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(); 
+5
source

Source: https://habr.com/ru/post/1270224/


All Articles