16

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",
  }
}
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
tvonk13
  • 163
  • 1
  • 1
  • 5
  • Without having any knowledge what `pg.Client` is, can you simply just console log `query` ? You can see what methods are available, perhaps there's an error when making new `pg.Client` object? – jdmdevdotnet Jul 26 '17 at 14:13
  • `query.on` has been removed from node-pg 7. See https://node-postgres.com/guides/upgrading for how to properly handle rows. – Denys Séguret Jul 26 '17 at 14:14
  • 1
    never used that lib, but from a quick glance, I don't see anything about `.on` in the docs. They are using callbacks, promises or `await/async` rather than events – baao Jul 26 '17 at 14:14
  • Oh that explains so much. Thanks for the clarification and link! @DenysSéguret – tvonk13 Jul 26 '17 at 14:19

3 Answers3

21

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();
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • 7
    Attention, you can't use keyword `await` outside of an `async` function. Put your code inside of a function, and prefix "function" with `async`. – Fabien Haddadi Nov 09 '18 at 08:12
  • var res = await client.query("SELECT * FROM json_test"); This row raises a blocking exception: UnhandledPromiseRejectionWarning, because you can't avoid handling promise rejection. – Peter Mar 26 '19 at 09:31
  • @Peter put this code into a try/catch block. This QA isn't really about how to handle promises and async/await so I think this is out of scope – Denys Séguret Mar 26 '19 at 13:18
6

this is how it works for me :

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

source : https://node-postgres.com/features/connecting

Houda M
  • 123
  • 1
  • 8
3

As Mentioned by Denys Séguret in Answer, the function query.on is deprecated. And if you are a beginner and want to get a quick connection to try out your queries without being bothered by async/await functionality. You can try the below code:-

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()
})
Suhas Chikkanna
  • 1,292
  • 5
  • 20
  • 34