HTML and CSS Reference
Don't Forget Your Indexes
The code presented earlier doesn't create any structures known as indexes on the collection. Although this works
passably well when you have a small number of users, it means that MongoDB needs to look through every doc-
ument of the collection to find users by their ID. To speed up this and other queries, you need to tell MongoDB
how to create indexes for its collections much in the same way you would in an RDBMS. From the mongo shell,
you can run the following:
This ensures there is an index on the user_id field in the users collection. See www.mongodb.org/display/
DOCS/Indexes for more details.
After the database methods, the three routes for the game are defined. The first route, /game , ensures that
the user is authenticated by wrapping the response in the aforementioned authenticated call. It then grabs
the user's object from the database, calculates the time to the next click, and renders the game.ejs view.
The click method, which is where the application POSTs clicks by the user, first grabs the user object
from the database and then tries to click the user. If the click succeeds, it returns clicked:true , the updated
user object (which contains the click count), and the newly calculated next click time; otherwise, it returns
clicked:false . The method uses Express's res.json method to return JSON back to the client, which
can be easily parsed and processed by jQuery.
Finally, the top-ten method simply returns the JSON for the top 10 clickers as JSON.
Finishing Blob Clicker
To finish the Blob Clicker game, the last piece needed is the game.ejs file, which contains the code for the
game. Because the game in this case is extremely simple, rather than pull in the Quintus engine, the code just
uses a few jQuery calls to update the page.
Add the code in Listing 20-6 to a new file in the views/ directory called game.ejs .
Listing 20-6: The view/games.ejs file
<link href='/style.css' rel='stylesheet' type='text/css' />
<meta name="viewport" content="width=device-width, ↵
user-scalable=0, minimum-scale=1.0, maximum-scale=1.0"/>
<h1><%= user.name %></h1>
<div id='blob'>Click Me</div>
<div id='clicks'><%= user.clicks %></div>