0

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,

zoint
  • 108
  • 2
  • 15
  • Your question is a bit hard to follow, but you should look at https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron – JohnnyHK Mar 13 '17 at 02:30

1 Answers1

1

mongoDbHandleLoad() contains asynchronous code (the calls to MongoDB) , so it's going to return undefined always before your code reaches the line return JSON.stringify(docs[docs.length-1]);.

You should use callbacks or Promises to get back your result.

I think first you should study a bit about asynchronous code in Javascript, in particular how are the conventions Node.js.

Antonio Val
  • 3,200
  • 1
  • 14
  • 27