nodejs + pg 用回调做 crud

Posted

技术标签:

【中文标题】nodejs + pg 用回调做 crud【英文标题】:nodejs + pg do crud with callback 【发布时间】:2015-10-23 14:31:51 【问题描述】:

我正在学习 nodejs express + pg。如果我想做crud,我应该使用第一种方法还是第二种方法? 有什么区别吗?

var query = "SELECT EXISTS(SELECT * FROM table WHERE user_email = '" + user_email + "')";

// 1
var result = dbClient.query(query);
console.log(result);
console.log(result._result.rowCount);

// 2
dbClient.query(query, function(err, result) 
  console.log(result);
  console.log(result.rows[0].exists);
);

连接

...
var conString = "postgres://db_admin:pwd@localhost/databasename";
var dbClient = new pg.Client(conString);
dbClient.connect();

【问题讨论】:

【参考方案1】:

我会选择:

// 2
dbClient.query(query, function(err, result) 
  if (err) 
    // do something with err
  
  else
    console.log(result);
    console.log(result.rows[0].exists);
  
);

或者你可以:

如文档所示:

    var query = client.query('select name from person');
    var rows = [];
    query.on('row', function(row) 
      //fired once for each row returned
      rows.push(row);
    );
    query.on('end', function(result) 
      //fired once and only once, after the last row has been returned and after all 'row' events are emitted
      //in this example, the 'rows' array now contains an ordered set of all the rows which we received from postgres
      console.log(result.rowCount + ' rows were received');
    )

但是,当您遇到深度嵌套的回调时,我建议您考虑使用 Promise。

见:

Using node-postgres via promises/A+ Manually promisifying pg.connect with Bluebird https://***.com/a/19282657/2026508 https://github.com/brianc/node-postgres/wiki

【讨论】:

@user1775888,链接更新,参考pg-promise ;)

以上是关于nodejs + pg 用回调做 crud的主要内容,如果未能解决你的问题,请参考以下文章

使用 LIMIT / ORDER BY 和 pg Postgres NodeJS 作为参数

nodejs中的异步回调机制

从nodejs运行bash命令[重复]

nodeJs回调简单的例子

nodejs模块pg操作postgres数据库

NodeJS 和 MongoDB:有没有办法监听集合并在集合有新文档时调用回调?