2
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)
1
  • not related to your problem, but: are you using pg-promise? If so, you should definitely use its built-in query-building system (like client.query('SELECT * FROM $1', tablename)) instead of using string concatenation. Imagine req.body.tablename was [yourtablename]; DROP TABLE [yourtablename]; --... xkcd.com/327 Commented Mar 22, 2018 at 18:24

1 Answer 1

2

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;
        }
Sign up to request clarification or add additional context in comments.

2 Comments

I also tried like that. but in that case, I received other errors like this: { error: sorry, too many clients already....
That sounds like the root cause of your problem. Why do you have other clients connecting? You should have one client and close it when you finish querying the DB

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.