HTML and CSS Reference
In-Depth Information
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:
db.users.ensureIndex({user_id:1});
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
<!DOCTYPE html>
<html>
<head>
<title>Blob Clicker</title>
<script src="//code.jquery.com/jquery-1.7.2.min.js"></script>
<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"/>
</head>
<body>
<div id="fb-root"></div>
<div id="main-screen">
<h1><%= user.name %></h1>
<div id='blob'>Click Me</div>
<div id='clicks'><%= user.clicks %></div>
 
 
Search WWH ::




Custom Search