0

I am pooling connections to my Postgres DB with pg-pool. I am having trouble, however, sending the results of my queries to the frontend. I assumed that I could use res.send as usual but it is not recognized (I also tried return). Here is my function:

exports.featList = function (req, res) {
 pool.connect(function(err, client, done) {
  if (err) {
   return console.error('error fetching client from pool', err);
  }
  client.query('SELECT * FROM book WHERE featured=true', function (err,res) {
   var json = JSON.stringify(res.rows);
   return json;
   client.release();
 });
});

1 Answer 1

0

It seems that is not returning the results because in the callback of the client.query you are redeclaring the res variable so you can't access the response object. If you rename this variable from res to results it will be able to return the results to the client:

exports.featList = function (req, res) {
  pool.connect(function (err, client, done) {
    if (err) {
      return console.error('error fetching client from pool', err);
    }
    client.query('SELECT * FROM book WHERE featured=true', function (err, results) {
      var json = JSON.stringify(res.rows);
      res.json(json);
      client.release();
    });
  });
}
Sign up to request clarification or add additional context in comments.

7 Comments

Oops, thanks, I actually just mistyped that (had it right in the actual code). I am starting to think that my issue is including the sending code within client.query. It needs to go outside I believe, just working on where.
@eabates the approach feel wrong because you should not create a connection on every request and it should not live in a middleware. You have to move the pool.connect into another file/lib that will be the database connector and when you boot the application to connect to the db. This file/lib should have a function that will return the client when needed (in the middleware in your case)
Actually I had to do client-release before res.send.
Hm, I do connect to the database in a separate module but as far as I understand pool.connect is the way to put a single client into the pool (and then remove it if it is "idle"). I have been monitoring my connections with `pg_stat_activity' and they do ebb and flow properly...
I wasn't aware of the node-pg-pool. What is the difference with the node-postgres pool? I thought that this is what you were using. Did the answer above resolve your issue?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.