Atul K.
Atul K.

Reputation: 372

node.js - post response is not waiting for callback to complete

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);
                }
            });
        })
    }
});

Upvotes: 1

Views: 1162

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311845

toArray is async, so it provides its results via callback rather than returning them.

So that part should be:

sysInfo.find().toArray(function(err, docs) {
    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.end(docs);
});

Upvotes: 2

Related Questions