Reputation: 3313
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();
Upvotes: 1
Views: 169
Reputation: 24089
I would go with:
// 2
dbClient.query(query, function(err, result) {
if (err) {
// do something with err
}
else{
console.log(result);
console.log(result.rows[0].exists);
}
});
Or you could:
As shown in the docs:
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');
})
However, when you get to deeply nested callbacks, I would suggest looking into using promises.
See:
Upvotes: 1