I am new to Node.js and I am unable to return a value from one of my functions.
My code looks like this:
//Instantiate MongoClient
var mongo = require('mongodb').MongoClient;
//Express engine
var express = require('express');
//Assert library (Perhaps overkill if you are writing production-level code)
var assert = require('assert');
//URL for my mongo instance
var db_url = 'mongodb://localhost:27017/pynap';
var url = require('url');
//Instantiate express
var router = express();
//Get operation
router.get('/:id', function(req, res, next) {
var targetCollection = req.params.id.toUpperCase()
var resultArray = [];
console.log("Getting documents for collection: " + targetCollection);
mongo.connect(db_url, function(err, db){
assert.equal(null, err);
var cursor = db.collection(targetCollection).find();
var docCount = db.collection(targetCollection).count(function(err, result) {
console.log("Number of results: " + result);
if (result == 0) {
res.render('empty', {collection: targetCollection});
}
return result;
});
// This should return `result` from the above function
console.log(docCount);
cursor.forEach(function(doc, err){
assert.equal(null, err);
resultArray.push(doc);
}, function(){
db.close();
res.render('data', {
results: resultArray
});
});
});
});
module.exports = router;
I am trying to return result from one of my functions, so that the value gets assigned to docCount. When I print docCount I get the value undefined.
via rhillhouse
No comments:
Post a Comment