HTML and CSS Reference
In-Depth Information
"user" : "Tester 2", "clicks" : 15 }
{ "_id" : ObjectId("4fb946508137643c2ac40e0860"),
"user" : "Tester 3", "clicks" : 10 }
> db.clicks.drop();
> exit
Creating records in MongoDB is as easy as calling{..}) with the model
data in a JavaScript object.
Querying the collection is done by calling db.collectionName.find() either by itself to return all
the objects or with the properties that you want to match in a JavaScript object. For example, to find all users
with the user property set to "Tester," the command used earlier is
If you are looking for a single object, you can use db.collectionName.findOne({..}) . As
you might expect, you can also order and limit the results by calling sort and limit . Finally
db.collectionName.drop() can destroy the entire collection.
NOTE This scratches only the surface of what you can do with MongoDB. You can find more information
about MongoDB in the official MongoDB manual at
MongoDB provides a rich interface to query documents (including querying deep into nested documents),
but the basics shown here are all that you need for the Blob Clicker game in this chapter.
Integrating MongoDB into the Game
Because Node.js works in an asynchronous manner, interacting with any external resources such as a database
tends to be callback-heavy and results in heavy nesting that can make it hard to follow the application logic.
In a larger app, the solution to this would be to use something such as the promise pattern, which was dis-
cussed in Chapter 8. In the case of Blob Clicker , another solution is to separate the database code from the rest
of the code so that it's easier to follow the flow of the actual pages.
To add database support into the game, replace the dummy app.get("/game"...) command at the end
of the web.js file with the code in Listing 20-5 . This code sets up three database methods— fetchUser ,
clickUser , and topTen —that are then used by the application's routes.
Listing 20-5: Blob Clicker DB and Routes code
var clickTime = 5000,
dbMethods = {};
require("mongodb").connect(process.env.MONGOHQ_URL ||
{}, function(error,db) {
db.collection('users', function(err, collection){
dbMethods.fetchUser = function(session,callback) {
collection.findOne({ user_id: session.user_id },
function(error,user) {
Search WWH ::

Custom Search