Skip to content
brianc edited this page May 26, 2011 · 49 revisions

Thanks to g40

how do I know what values are on the row object ?

The row object has properties which align to the column names returned from the query.

Given a table users with columns 'name' and 'age' doing select * from users would return you a result object with an array of row objects. Each row object would have the properties name and age. Example:

client.query('SELECT * FROM users`, function(err, result) {
  console.log('name: %s and age: %d', result.rows[0].name, result.rows[0].age);
  //since the row object is just a hash, it can be accessed also as follows
  console.log('name: %s and age: %d', result.rows[0]['name'], result.rows[0]['age']);
});

can I iterate across the columns in the recordset to dynamically display column names ?

Why, yes. Yes you can.

client.query(..., function(err, result) { 
  var firstRow = result.rows[0];
  for(var columnName in firstRow) {
    console.log('column "%s" has a value of "%j"', columnName, firstRow[columnName]);
  }
});
Clone this wiki locally