1

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();
rudolph1024
  • 962
  • 1
  • 12
  • 32
user1775888
  • 3,147
  • 13
  • 45
  • 65

1 Answers1

1

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:

Community
  • 1
  • 1
jmunsch
  • 22,771
  • 11
  • 93
  • 114