mongoose.js server - res.write for query data does not send data back to client

I am trying to setup a simple mongoose test server that reads users in the Users collections and prints the username. I can't seem to get the res.write for the query data to show up at the client side

var mongoose = require('mongoose');
var db = mongoose.createConnection('localhost', 'bugtraq');
var schema = mongoose.Schema({ username : 'string', email : 'string' });
var User = db.model('User', schema);

var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});

    User.find().exec(function (err, users) {
        if(err) { res.write(err.message); }
        if(users) {
            users.forEach(function(u){
                console.log(u.username);
                return '<b>'+u.username+'</b>';
            });
        }
    });

    res.write('</body></html>');
    res.end();
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');

The server side output is

<html><head></head><body></body></html>

I do see the username in the console output

Any pointers welcome

You have two problems. First, the mongoose query is anynchronous, yet you're ending your response outside of it's callback, before the query actually happens (I had to reindent the code to make sure).

To make it work you'd need to end the response inside the callback function for User.find.

Secondly, you're not collecting output as you think. This line is wrong:

return '<b>'+u.username+'</b>';

You're returning the output of the find into thin air. You'll need to capture it if you want to return it in the response.

Putting it together, it might look something like this:

User.find().exec(function (err, users) {
    if(err) { res.write(err.message); }
    if(users) {
        // here make a buffer to store the built output ...
        var output = [];
        users.forEach(function(u){
            // (you saw this console output because this loop is happening, it's
            // just happening after your response has been ended)
            console.log(u.username);

            // ... then in each iteration of the loop, push to the buffer
            output.push('<b>'+u.username+'</b>');
        });
    }

    // finally, finish the response in the `find` callback.
    res.end(output.join() + '</body></html>');
});