Node.JS HTTP Response Returns Nothing?

I am attempting to iterate through a MongoDB cursor object and return all records from a collection and then using the respond method in Node outout to the browser.

The problem I have is no response seems to be fired.

I have tried putting response.end() inside the loop but it then doesn't iterate through the results.

I have tried response.end() in different places also. Here is the code

db.open(function(err, db) {
            if(!err) {
                console.log("Nodelistr is connected to MongoDB\n");
                response.writeHead(200);

                db.collection('todo', function(err, collection){            
                    collection.find(function(err, cursor) {
                        cursor.each(function(err, doc) {
                            for(docs in doc){
                                if(docs == "_id"){
                                }else{
                                    var test = docs + " : " + doc[docs];
                                }
                            }
                            data = data.toString("utf8").replace("{{TEST}}", test);
                            response.write(data);

                            //console.dir(doc);
                        })           
                        response.end();         
                    });
                });

            };

        });

I can't figure out what you're trying to do with the uninitialized data variable and the documents as you iterate over them, but the general problem is that you need to wait to call response.end(); until you've hit the end of the cursor. That's indicated by doc being null in the cursor.each callback.

The middle part of your code should follow this general approach:

db.collection('todo', function(err, collection){            
    collection.find(function(err, cursor) {
        cursor.each(function(err, doc) {
            if (doc) {
                ...  // initialize data from doc
                response.write(data);
            } else {
                // doc is null, so the cursor is exhausted
                response.end();         
            }
        })           
    });
});