Blog

  • Integrate PostgreSQL with Nodejs

    Posted by Md Imroz Alam | Last Updated: 13-Jan-17

    PostgreSQL NodeJS

    configure with postgresql 

    var knexReq = require('knex');
    global.objection = require('objection');
    global.Model = objection.Model;

    Initialize knex connection

    global.knex = knexReq({
        client: 'pg',
        useNullAsDefault: true,
        connection: {
            host: '127.0.0.1',
            port: "5432",
            user: 'testUser',
            password: 'user@123',
            database: 'dbAdmin'
        }
    });

    ----User.js-------
    // schema for user table with orm 

    var schemaPromise = knex.schema.createTableIfNotExists('User', function(table) {
        table.increments('id').primary();
        table.string('email');
        table.string('password');
    }).then(function(data) {
        console.log("User Table added ");
    });
    // Alter table User
    knex.schema.hasColumn('User', 'Address').then((isColumn) => {
        if (isColumn != true) {
            knex.schema.table('User', function(table) {
                table.string('Address'); 
            }).then(function(data) {
                console.log("Address Column added");
            });
        }
    });
    function User() {
        Model.apply(this, arguments);
    }
    User.tableName = 'User';
    User.jsonSchema = {
      type: 'object',
      required: ['email','password'],
      properties: {
        id: {type: 'integer'},
        email: {type: 'string', minLength: 1, maxLength: 255},
        password:{type:'string',minLength:1,maxLength:10},
        Address:{type:'string'}
      }
    };
    Model.extend(User);
    module.exports = User;

    ------- End User.js ---------------------

    set global access User table instance 

    global.domain = {}
    domain.User = require("User.js")
    module.exports = domain


    Insert data in user table

    domain.User.query().insert({
          email: "testUser@gmail.com",
              password: "123456",
              Address:"delhi"
          }).then(function(databaseReturn) {
    });

    retrieve data of User table

    domain.User.query().where({
                      'email': 'testUser@gmail.com"
                  }).select().then(function(data) {
                     console.log("user detail: ",data);
    });

    I hope this will be helpful.

    Thanks
     

Tags: nodejs

View All PostsLeave a Comment
comments powered by Disqus

Mobile Applications

Video Content

Bigdata & NoSQL

SaaS Applications

Miscellaneous

Archives


Alexa Certified Site Stats for www.oodlestechnologies.com