I want to send a json data via Mongodb query from the server side to client side. I have handled my query of database and connection stuff as you can see.
function mongoDbHandleLoad()
{
MongoClient.connect(MongoDBURL, function(err, db)
{
/*
db.createCollection('user', {strict:true}, function(err, collection) {
if(err)
return console.dir(err);
});
*/
db.collection('user', function(err, collection) {
if(!err)
{
collection.find().toArray(function(err, docs) {
if(!err)
{
var intCount = docs.length;
var responseBody;
if(intCount > 0)
{
console.log("responseBody in mongodb handle", JSON.stringify(docs[docs.length-1]));
return JSON.stringify(docs[docs.length-1]);
}
}
});
}
});
});
/*
if(docs != null)
{
console.log("docs", docs);
return resParam.json(docs); //return the first document found
}
*/
}
And I send a test json data successfully with this code snippet.
if(str.localeCompare(controlPathDatabaseLoad) == 0)
{
console.log("controlPathDatabaseLoad");
mongoDbHandleLoad();
res.setHeader('Content-Type', 'application/json');
res.writeHead(res.statusCode);
res.write(JSON.stringify(testJSON));
res.end();
}
When I wanted to send the data "JSON.stringify(docs[docs.length-1])" inside of mongoDbHandleLoad() function, even though I changed function with callback, I couldn't do properly. I take undefined value from mongoDbHandleLoad function. How can I modify to code to take proper value of "JSON.stringify(docs[docs.length-1])".
Thanks in advance,