Eric Lee
Eric Lee

Reputation: 121

Cannot read property 'query' of undefined in Node & Postgresql

const pool = new pg.Pool(config);
var tablename = req.body.tablename;

pool.connect(function (err, client, done) {
    var query_get_value = 'SELECT * FROM '+ tablename;
    client.query(query_get_value, function (err, result) {
        done();
        if (err) {
                throw err;
        }
        var rows = result.rows;
.....

this code runs correctly for a while, but a few seconds later, I received following errors:(I call this function repeatedly on the view side using setInterval function)

 client.query(query_get_value, function (err, result) {
                   ^

TypeError: Cannot read property 'query' of undefined
    at /var/node_project/controllers/index.js:630:10
    at client.connect (/var/node_project/node_modules/pg-pool/index.js:219:9)
    at Connection.connectingErrorHandler (/var/node_project/node_modules/pg/lib/client.js:123:14)
    at Connection.emit (events.js:127:13)
    at Socket.<anonymous> (/var/node_project/node_modules/pg/lib/connection.js:117:12)
    at Socket.emit (events.js:127:13)
    at addChunk (_stream_readable.js:269:12)
    at readableAddChunk (_stream_readable.js:256:11)
    at Socket.Readable.push (_stream_readable.js:213:10)
    at TCP.onread (net.js:598:20)

Upvotes: 2

Views: 6866

Answers (1)

Stretch0
Stretch0

Reputation: 9251

You are probably getting getting an error and therefore client doens't have the method query because it is undefined.

You can easily wrap it in an if/else block to make sure client is set:

pool.connect(function (err, client, done) {
        if(err) {
            console.log(err)
        }else{
            var query_get_value = 'SELECT * FROM '+ tablename;
        client.query(query_get_value, function (err, result) {
            done();
            if (err) {
                    throw err;
            }
            var rows = result.rows;
        }

Upvotes: 2

Related Questions