I'm learning nodejs
express
+ pg
. If I want to do crud, should I use the first method or the second?
Does it make any difference?
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);
});
connect
...
var conString = "postgres://db_admin:pwd@localhost/databasename";
var dbClient = new pg.Client(conString);
dbClient.connect();
答案 0 :(得分: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');
})
然而,当你进行深度嵌套的回调时,我建议使用promises。
见: