Integrate PostgreSQL with Nodejs
Posted By : Md Imroz Alam | 10-Jan-2017
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
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
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.