This is connection.js
var MongoClient = require('mongodb').MongoClient;
var db_singleton = null;
var getConnection= function getConnection(callback) {
if (db_singleton) {
callback(null,db_singleton);
} else {
var connURL = "mongodb://localhost:27017/testdb";
MongoClient.connect(connURL,function(err,db){
if(err)
console.log("Error creating new connection "+err);
else
{
db_singleton=db;
console.log("created new connection");
}
callback(err,db_singleton);
});
}
};
module.exports = getConnection;
And this is product.js
var getConnection = require('../../connection.js');
var products = null;
getConnection(function(err,db) {
var collection = db.collection("products");
collection.find().toArray(function(err, productsDB) {
products = productsDB;
})
});
console.log(products);
module.export = products;
console.log(products) is always null.
But it should be object.I would like to cache variable when server starts.
Related
password saved on db (when user registered) changes when user update his/her details.I have done below code for updation in routes/api.js
var User = require('../models/user');
module.exports = function(router) {
router.put('/profileupdation2/:ssn/:firstname/:lastname/:username/:email/:age/:phno',function(req,res) {
var ssn1 = req.params.ssn;
var fname = req.params.firstname;
var lname = req.params.lastname;
var username = req.params.username;
var email1 = req.params.email;
var age1 = req.params.age;
var phno1 = req.params.phno;
User.findOne({ssn:ssn1}, function(err,user) {
if(err) throw err;
console.log(user);
if(!user){
console.log('No user found');
} else {
user.ssn = ssn1;
user.firstname = fname;
user.lastname = lname;
user.username = username;
user.email = email1;
user.age = age1;
user.phno = phno1;
user.update(function(err) {
if (err) {
console.log(err);
} else {
console.log('updated!!!');
}
});
}
});
});
return router; //returns the router object to server
};
I'm trying to create a custom command in nightwatch that runs a query on a Postgres database and returns the result. The query runs just fine and outputs the result to the console but then the execution of the test stops. I don't understand how callbacks work. How can I fix this custom command?
exports.command = function(sql, callback) {
var self = this;
var pg = require('pg');
var conString = self.globals.testinfo.connectionString;
var db = new pg.Client(conString);
db.connect(function(err) {
if(err) {
console.error('could not connect', err);
}
else {
db.query(sql, function(err, result) {
if(err) {
console.log('error running query', err);
}
else {
console.log(result.rows.length);
db.end();
}
});
}
}),
function(result) {
if (typeof callback === 'function') {
callback.call(self, result);
}
}
return this;
};
I had to wrap the database connection in a perform command to get this working. I'm not sure if this is the best way to handle the callback, but it works. Here's the updated version of the custom command:
exports.command = function(sql,callback) {
var self = this;
var pg = require('pg');
var cs = self.globals.testinfo.connectionString;
self.perform(function(self,done) {
pg.connect(cs,function(err,db,done) {
if(err) {
return console.error(err);
}
db.query(sql, function(err,result) {
done();
if(err) {
return console.error(err);
}
console.log(result.rows.length);
callback(result.rows[0]);
});
});
pg.end();
done();
});
};
Here's how I call the custom command in the test:
browser.myCustomCommand('select * from table limit 1;', function(row) {
browser.assert.deepEqual(row.column,'some value');
});
Can you try this:
exports.command = function(sql, callback) {
var self = this;
var pg = require('pg');
var conString = self.globals.testinfo.connectionString;
var db = new pg.Client(conString);
var cb= function(result) {
if (typeof callback === 'function') {
callback.call(self, result);
}
};
db.connect(function(err) {
if(err) {
console.error('could not connect', err);
cb(false);
}
else {
db.query(sql, function(err, result) {
if(err) {
console.log('error running query', err);
cb(false);
}
else {
console.log(result.rows.length);
db.end();
cb(true);
}
});
}
}),
return this;
};
And in your test :
'test' : function(browser){
browser.yourCommandName(sql,function(result){
console.log(result); //if connect is good result would be true and false if fail to connect.
});
}
Ps: the result in callback can be as an object(contain rows or anything you want), instead of boolean only in this example.
And Nightwatch is used for end-to-end testing, it is not aimed for Database testing,i think you should find another framework to test database connection.
My problem is, that the controller just send an undefiend and not the data from http of service. I inspect it with chrome. I am new at ionic. By calling the AppSqliDBFactory.getMasterdataId() method, it shows an undefiend, also at the scope variable.
.controller('ReadMasterdataCtrl', function ($scope, $state, $ionicNavBarDelegate, MasterdataService, AppSqliDBFactory){
$scope.masterdataId;
$scope.masterdataData;
AppSqliDBFactory.getMasterdataId().then( function (masterdata){
$scope.masterdataId = masterdata[0].masterdataId;
}).catch(function (err){
console.log(err);
});
//here is the error -> no data at "$scope.masterdataData = masterdata;"
MasterdataService.getMasterdataDB($scope.masterdataId)
.then(function (masterdata) {
$scope.masterdataData = masterdata;
console.log("getMasterdataDB respont");
console.log($scope.masterdataData);
}).catch(function (err) {
console.log(err);
});
})
//Service
.factory('MasterdataService', function ($q, $http, SERVER_URL) {
//Create JSON Object
var srv = {};
//Array for JSON Objects
srv.masterdata = [];
srv.getMasterdataDB = function (masterdataId) {
var deferred = $q.defer();
var masterdata;
var masterdataId = masterdataId;
var baseUrl = 'xxxx';
$http.get(SERVER_URL + baseUrl + masterdataId).success(function (response){
masterdata = response[0];
console.log(masterdata);
return deferred.resolve(masterdata);
}).error(function (err){
return deferred.reject(err);
});
return deferred.promise;
//return srv.getMasterdata();
};
// Public API
return {
getMasterdataDB: function ( masterdataId) {
return $q.when(srv.getMasterdataDB( masterdataId));
}
};
});
Simplified:
AppSqliDBFactory.getMasterdataId().then(function (masterdata) {
$scope.masterdataId = masterdata[0].masterdataId;
});
MasterdataService.getMasterdataDB($scope.masterdataId).then(function (masterdata) {
$scope.masterdataData = masterdata;
});
When MasterdataService.getMasterdataDB() is called, AppSqliDBFactory.getMasterdataId() may not have been resolved yet, so $scope.masterdataId can be undefined (which is probably what is happening in your case).
You have to call AppSqliDBFactory.getMasterdataId() after AppSqliDBFactory.getMasterdataId() has been resolved:
AppSqliDBFactory.getMasterdataId().then(function (masterdata) {
$scope.masterdataId = masterdata[0].masterdataId;
MasterdataService.getMasterdataDB($scope.masterdataId).then(function (masterdata) {
$scope.masterdataData = masterdata;
});
});
Or with chaining:
AppSqliDBFactory.getMasterdataId().then(function (masterdata) {
$scope.masterdataId = masterdata[0].masterdataId;
return MasterdataService.getMasterdataDB($scope.masterdataId);
}).then(function (masterdata) {
$scope.masterdataData = masterdata;
});
I would like to know how can you check the row count of the query in PostgreSQL in node.js
I have this code for the meantime.
var client = new pg.Client(conString);
client.connect();
var query = client.query("SELECT * FROM users");
query.on('row', function(row) {
console.log(row);
});
var client = new pg.Client(conString);
client.connect();
client.query("SELECT * FROM users", function(err, result) {
console.log("Row count: %d",result.rows.length); // n
});
Another options is to use the rowCount property! Like this:
var pg = require('pg');
var pgClient = new pg.Client();
pgClient.connect();
var pgQuery = pgClient.query("SELECT * FROM information_schema.tables;");
pgQuery.on('error', function(err) {
pgClient.end();
console.error(err);
});
pgQuery.on('end', function(result) {
pgClient.end();
console.log(result.rowCount);
});
or like this:
var pg = require('pg');
var pgClient = new pg.Client();
pgClient.connect();
var pgQuery = pgClient.query("SELECT * FROM information_schema.tables;", function(err, result) {
pgClient.end();
if (err) return console.error(err);
console.log(result.rowCount);
});
I want build a class for wrapping database connection. This is my code ('db.js' file):
var mongodb = require('mongodb');
var Class = function() {
this.db = null;
var server = new mongodb.Server('127.0.0.1', 27017, {auto_reconnect: true});
db = new mongodb.Db('myDB', server);
db.open(function(error, db) {
if (error) {
console.log('Error ' + error);
} else {
console.log('Connected to db.');
this.db = db;
}
});
};
module.exports = Class;
Class.prototype = {
getCollection: function(coll_name) {
this.db.collection(coll_name, function(error, c){ // <--- see error below
return c;
});
}
}
exports.oid = mongodb.ObjectID;
Then, my test code ('test.js' file):
var DB = require('./db');
var myDB = new DB();
myDB.getCollection('myCollection'); // <--- error: Cannot call method 'collection' of null
You are missing "this" in front of "db". eg:
this.db = new mongodb.Db('myDB', server);
And the line next to it.