Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Integrate Postgresql with Node JS

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 352
    Comment on it

    Many Programmers feel comfortable to use Postgre SQL rather than MongoDB, member of MEAN Stack.

    We are going to integrate Postgresql with NodeJS

    To install NodeJS, please go through this Article

    Now, when we are finished with Installation of NodeJS.

    We are going to install Postgres

    first, run a command

    npm install pg --save

    Sometimes it doesn't work, so use sudo

    sudo npm install pg --save

    after completing the installation, We will be using the below code in our file to execute query.
     

    var pg = require('pg');
    var conn = 'postgres://postgres:postgres@localhost:5432/first_app_developement';
    
    var client = new pg.Client(conn);
    client.connect();

    Now, lets break each line to understand

    var pg = require('pg');

    In the above line, we include postgres module by require method and create an object named pg.

    var conn = 'postgres://[username]:[password]@[host]:[port]/[database_name]'

    Now, we are including postgres URL,

    [username] postgres username
    [password] postgres password
    [host] your URL (as we are in Developement phase, we will include localhost)
    [port] port assigned to Postgres
    [database_name] at last is your database name

    I have simplified, for your usability

    var connectionString = 'postgres://postgres:postgres@localhost:5432/first_app_developement';

    Next we have to create an object for our postgres client

    var client = new pg.Client(conn);

    In this we have created an object of Client with corresponding database.

    At last we need to connect our Client

    client.connect();

    Viola, we are connected !!!.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: