本文介绍了什么是使用node.js postgresql模块的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Heroku上编写node.js应用程序,并使用。我无法弄清楚为需要查询数据库的每个请求获取客户端对象的正确方式。



文档使用如下代码:

  pg.connect(conString,function(err,client){
//使用客户端在这里执行
});

但是你确实不需要调用 pg.connect 在每个使用数据库权限的函数中?我已经看到了:

  var conString = process.env.DATABASE_URL || TCP:// postgres的:1234 @本地/ postgres的; 
var client = new pg.Client(conString);
client.connect();
//客户端是全局的,所以你可以在任何地方使用它

我倾向于第二种选择,因为我相信Heroku的免费数据库实例无论如何只限于一个连接,但是这样做有什么缺点吗?我是否需要检查我的客户端对象是否每次都在我使用之前连接?

解决方案

我是。首先,我很抱歉,文件没有明确说明正确的选项:这是我的错。我会尽力改进它。我刚刚写了来解释这个,因为执行此操作。


I am writing a node.js app on Heroku and using the pg module. I can't figure out the "right" way to get a client object for each request that I need to query the database.

The documentation uses code like this:

pg.connect(conString, function(err, client) {
  // Use the client to do things here
});

But surely you don't need to call pg.connect inside every function that uses the database right? I've seen other code that does this:

var conString = process.env.DATABASE_URL || "tcp://postgres:1234@localhost/postgres";
var client = new pg.Client(conString);
client.connect();
// client is a global so you can use it anywhere now

I am leaning toward the second option since I believe the free database instance for Heroku is limited to one connection anyway, but are there any drawbacks to doing it this way? Do I need to check if my client object is still connected every time before I use it?

解决方案

I'm the author of node-postgres. First, I apologize the documentation has failed to make the right option clear: that's my fault. I'll try to improve it. I wrote a Gist just now to explain this because the conversation grew too long for Twitter.

One very helpful thing is to centralize all access to your database in your app to one file. Don't litter pg.connect calls or new clients throughout. Have a file like db.js that looks something like this:

module.exports = {
   query: function(text, values, cb) {
      pg.connect(function(err, client, done) {
        client.query(text, values, function(err, result) {
          done();
          cb(err, result);
        })
      });
   }
}

This way you can change out your implementation from pg.connect to a custom pool of clients or whatever and only have to change things in one place.

Have a look at the node-pg-query module that does just this.

这篇关于什么是使用node.js postgresql模块的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 05:46