Post response is not waiting for callback to complete

84 views
Skip to first unread message

Atul K

unread,
Jan 30, 2015, 5:33:23 AM1/30/15
to nod...@googlegroups.com

I am working on node.js http server. The Server is connected to mongodb. I am requesting a post request to the server to get documents from mongodb. But the post response is not waiting for mongodb callback to complete. And therefore I am not getting required output on the client side. How to handle this?

http.createServer(function(request, response) {
    if(request.method == "POST") { 
        var body = '';
        request.on('data', function(chunk) {
            console.log(chunk.toString());
            body += chunk;
        });
        request.on('end', function() {
            MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
                if(err) {
                    console.log("We are not connected");
                }   
                else {
                    var sysInfo = db.collection('sysInfo');
                    var jsonObj = sysInfo.find().toArray();
                    response.writeHead(200, {'Content-Type': 'text/plain'});
                    response.end(jsonObj);
                }
            });
        })
    }
});

Ryan Schmidt

unread,
Jan 31, 2015, 1:51:51 PM1/31/15
to nod...@googlegroups.com
I'm not sure which node mongodb module you're using, but undoubtedly an operation like find() will be asynchronous--a request will be sent to the mongodb server, and it will take some time to complete, and when it is completed, your callback will be called with the resuls. You will need to consult the documentation of whichever node mongodb module you're using to see how it expects you to provide the callback that it will call when the asynchronous operation is complete.

Oleg Verych

unread,
Jan 31, 2015, 3:17:33 PM1/31/15
to nod...@googlegroups.com
>                     var sysInfo = db.collection('sysInfo');
>                     var jsonObj = sysInfo.find().toArray();

to.Array(function(err, dataArray)){

>                     response.writeHead(200, {'Content-Type': 'text/plain'}); 
>                     response.end(jsonObj); 
}

 
I'm not sure which node mongodb module you're using, but undoubtedly an operation like find() will be asynchronous

Yes it is as with `toArray(callback)`.
_________

Reply all
Reply to author
Forward
0 new messages