Reputation: 372
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