0

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?

faizanjehangir
  • 2,771
  • 6
  • 45
  • 83
  • 1
    possible duplicate of [How to return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Blakes Seven Aug 17 '15 at 03:46
  • @BlakesSeven: The question is subtly different. If you read the question carefully it's clear that he already understands that he needs to handle it asynchronously. He only doesn't understand how to write a function that accepts a callback. – slebetman Aug 17 '15 at 04:01

1 Answers1

2

Just add another argument to the function and treat it as a function (there's no additional syntax, just pretend it's a function):

getUserRequestObject : function(email, number, my_own_callback){

        /* .. lots of code .. */

        // return documentObj;
        my_own_callback(documentObj); // this is how it's done
}
slebetman
  • 109,858
  • 19
  • 140
  • 171