query.on is not a function

两盒软妹~` 提交于 2019-12-03 10:37:38

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

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

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()
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!