I wrote a “Twitter clone” today at work to get my head around some of the new technology we’re using at EMU Marketing. Node.js is our shiny new server-side language/toy. Evented I/O is pretty cool, but it’s also a little confusing at first. Or it has been for me, anyway.
The following 42 line snippet is the whole application! I thought I’d post it because it demonstrates quite a lot of capability that these kind of applications can crank out in not-too-much code.
Lines 1-5 load some libraries, particularly Connect (framework), Mongoose (MongoDB) and Underscore (for HTML templating).
Lines 7-11 connect to the database server, set up the database connection and define a model (similar to a MySQL table).
Line 13 reads our Underscore template in. Writing lots of inline HTML is no fun at all.
Lines 35-40 set up the server with some Connect middleware layers. The Connect module bodyDecoder makes the data from the form POST available without extra work — very handy. The router module makes URL-based parsing super easy.
Line 16 is called by the router when a client sends a GET request to ‘/’. The anonymous function outputs a header (Line 17); queries the MongoDB via Mongoose and sorts by time, descending (18); debugs the query to the server output (19); and outputs HTML after the query object is fed through the template. The HTML includes a form before any of the query outputs — this form POSTs to ‘/’ with the new “chirps.”
Line 24 is called when that form POSTs to ‘/’. The request is then logged to the server output (25). After testing that the POST makes at least a little sense (26), it builds a new “record” to be “inserted” into MongoDB, then saves it (27). Line 30-31 issues a redirect to get the browser to do a GET on ‘/’, showing the new data.
And that’s pretty much it!
Side note: Paul and I spent a long time trying to figure out how to sort in Mongoose. For some reason, it takes sort arguments completely differently that Mongo does. The difference is shown in commented-out line 18 and line 19.
Here’s the template file, if you’re curious:
I’m sorry that you ran into issues with mongoose. To be fair, this isn’t mongoose’s fault. It is a result of how node-mongodb-native handles sorting. I will make sure to make a note about that in the documentation. Feel free to ask questions at mongoosejs google groups.
Look forward to a major release of mongoose in the coming weeks.
Thanks for the reply! I understand that it’s not Mongoose’s fault now — I was just very frustrated after digging through Mongo and Mongoose documentation and not finding anything about what the syntax should be.
Mongoose is quite cool. Looking forward to the release!
Dude, you rock! This is what finally got me set up with a working mongoose connection. I’m on my way to web app city…
Thanks again.
Paul