Book Image

Learning Heroku Postgres

By : Patrick Rafael de Oliveira Espake
Book Image

Learning Heroku Postgres

By: Patrick Rafael de Oliveira Espake

Overview of this book

Table of Contents (17 chapters)
Learning Heroku Postgres
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Keyword List
Index

Connecting with Node.js


In order to connect to PostgreSQL with Node.js it is necessary to use the pg module. To make that possible, you have to add it to the dependency file called package.json. The following is just a code sample to help you understand the concept:

"dependencies": {   
"pg": "0.10.2",   
"express": "latest" 
}

Then use the pg module to connect to PostgreSQL through the DATABASE_URL environment variable in your code:

var pg = require('pg');
pg.connect(process.env.DATABASE_URL, function(err, client, done) {
  if(err) {
    return console.error('Client error.', err);
  }
  
  client.query('SELECT * FROM doctors', function(err, result) {
    done();

    if(err) {
      return console.error('Query error.', err);
    }
    
    console.log(result.rows);
  });
});