Scoping in node.js, mongodb + http server loop

I'm brand new to node.js (less than one hour).

I'm trying to bring up a simple http server that will read a mongodb collection and print the data to the browser window.

So far, I have:

var http = require ("http")
var mongodb = require('mongodb');

http.createServer(function(request, response) {
    var server = new mongodb.Server("127.0.0.1", 27107, {});
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write('Collection Data:<br>')
    new mongodb.Db('testdb', server, {}).open(function (error, client) {
      if (error) throw error;
      var collection = new mongodb.Collection(client, 'test_coll');
      collection.find({}, {limit:100}).each(function(err, doc) {
        if (doc != null) {
            console.dir(doc.text);
            response.write(doc.text)
        }
      });
      response.write("some stuff")
      response.end();
    });
}).listen(8080)

This puts the text of the collection items onto the console, but not to the browser window. I think this is because the response object is not in scope in the .each callback? Have I structured this the wrong way?

The problem is that response.end() is being called before your callback executes.

You'll have to move it inside, like this:

collection.find({}, {limit:100}).each(function(err, doc){
    if (doc != null) {
        console.dir(doc.text);
        response.write(doc.text)
    } else {
        // null signifies end of iterator
        response.write("some stuff");
        response.end();
    }
});

res.end has to happen AFTER the for loop inside the callback:

client.collection('test_coll', function(err, testColl) {
  testColl.find({}).each(function(err, doc) {
    if (err) {
        // handle errors
    } else if (doc) {
        res.write(doc._id + ' ')
    } else { // If there's no doc then it's the end of the loop
        res.end()
    }
  })
})