Counting and Aggregating with Mongoose

I did not let the beautiful sunshiny day keep me from spending too much time working on a project for displaying Twitter users talking about a specific topic. I decided to expand on my developments yesterday to actually read from the database, group over users, and sort the list to display to someone on my potential site.

The most significant challenge was figuring out how MongoDB actually works, but after some setup and searching the internet, I figured out how to use find() to capture all of the users in my database. I enhanced this work to perform all of the actions I wanted, including sending out html with the following bit of code:

var Twitusers = mongoose.model('Twit');


userList = "";
Twitusers.aggregate([
    {$match:{search:searchTerm}},
    {$group:{_id:'$username',count:{$sum:1}}},
    {$sort:{count:-1}}
    ], function(err, users) {
        if (err) {console.log(err);}
            for (i=0;i<users.length;i++) {
        userList = userList + users[i]['_id'] + 
        ": " + users[i]['count']  + "<br>";
    }   
        var html = 'We have started capturing data on the term(s) ' + searchTerm +
        ' and the top results (so far) are: <br>' + userList;
        res.send(html);
});

This expands on the form I created yesterday to now send out an ordered list of the usernames, along with the number of tweets for each user.

The next step in this is to clean up the code and make it a little more functional. I should probably aggregate over a particular time range, and not send out code through a post request, but there is a display and some functionality in code that I created, so that makes it a day!