This is my first experience with NodeJSand Mongo. I am handling all the database query handlers in a seperate JS file, exported as a module in another file, which handles the user requests. I want to search (findOne) user document from a collection table, and return it to the callee. But I cannot figure out how to register a callback and return the document, once the query execution completes..
Here is my code, where I call the method:
var record = mongoDataHandler.getUserRequestObject(credentials.email, "");
How to change this call, such that it should look like:
mongoDataHandler.getUserRequestObject(credentials.email, "", function (result){
//handle the result response here
});
Here is my getUserRequestObject, in another JS file (mongodatahandler.js):
var MongoClient = require('mongodb').MongoClient
, format = require('util').format;
var assert = require('assert');
var ds = require('../../server/datasources.json');
var dbMongoConnectorUrl = ds.MongoDBDev.url;
module.exports = {
getUserRequestObject : function(email, number){
var documentObj = null;
MongoClient.connect(dbMongoConnectorUrl, function(err, db) {
if (err) throw err;
console.log("Connected to Database");
var cursor = db.collection('UserRequestCode').find({"email": "someemail@gmail.com"}).sort( { _id: -1} ).limit(1);
cursor.each(function(err,doc) {
if (err) documentObj = {status:500, resp:err};
if (doc != null){
console.dir(doc);
documentObj = {status:200, resp:doc};
return;
}
});
});
return documentObj;
}
}
The object returned (documentObj) is always null. Which is because it is not registered to a callback function.
How should I register a callback here, so that my retrieved document from collection works asynchronously?