Integrate PostgreSQL with Nodejs

Posted By : Md Imroz Alam | 10-Jan-2017

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: "[email protected]",
          password: "123456",
          Address:"delhi"
      }).then(function(databaseReturn) {
});

retrieve data of User table

domain.User.query().where({
                  'email': '[email protected]"
              }).select().then(function(data) {
                 console.log("user detail: ",data);
});

I hope this will be helpful.

Thanks
 

About Author

Author Image
Md Imroz Alam

Md. Imroz Alam is a bright Web App Developer, he has good knowledge of Java, J2SE, Jsp, Servlet, jdbc. His hobbies are watching movie, playing carom.

Request for Proposal

Name is required

Comment is required

Sending message..