How do I use node-postgres in a server?

后端 未结 1 1773
孤城傲影
孤城傲影 2021-02-20 07:55

I\'m writing a Node.js web server that uses a Postgres database. I used to connect on each new request like this:

app.get(\'/\', function (req, res) {
  pg.conne         


        
相关标签:
1条回答
  • 2021-02-20 08:26

    I'm assuming you're using the latest version of node-postgres, in which the connection pooling has been greatly improved. You must now check the connection back into the pool, or you'll bleed the connections:

    app.get('/', function (req, res) {
      pg.connect(pgconnstring, function (err, client, done) {
        // do some stuff
        done();
      });
    });
    

    As for error handling on a global connection (#2, but I'd use the pool):

    client.on('error', function(e){
      client.connect(); // would check the error, etc in a production app
    });
    

    The "missing" docs for all this is on the GitHub wiki.

    0 讨论(0)
提交回复
热议问题