query.on is not a function

tvonk13 picture tvonk13 · Jul 26, 2017 · Viewed 16.4k times · Source

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

Answer

Denys Séguret picture Denys Séguret · Jul 26, 2017

query.on has been removed from node-pg 7.

See https://node-postgres.com/guides/upgrading for how to properly handle rows.

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