I am trying to fetch the number of records from Database using nodejs but the problem is that due to sync requests , I am not able to print them. When I try to print it inside the function , it prints fine but outside the function , it doesn't. I know it is due to sync behavior of JS but I want to do this (may be asynchronsly) . I am very new to Javascript and nodejs , so please guide me how can I do this. here is the code.
router.post('/numofrecs', function(req, res) {
var db = new Db('nmydb', new Server('localhost', '27017'));
db.open(function (err, db) {
db.authenticate('', '', function (err, result) {
var url = 'mongodb://localhost:27017/nmydb';
client.connect(url, function (err, db) {
que = new Array();
var questioncol = db.collection('allquestions');
questioncol.find({}).count(function (err, data) {
rec = data;
console.log("Num of rec:"+rec);
//inside the connect function , it prints fine here
});
console.log('Num of rec:'+ rec);
//but it doesnot print here outside the connect function and just print "undefined"