Schema design

Each player can simply be represented by a document with a single field for the name:

{ name: 'leo' }

User schema

We will use Mongoose for our data modeling. Let's start with designing our user schema. The schemas are placed in the models folder in the app. The following screenshot shows the folder structure. The schema will have one required field name, this is done by adding required: true to the name object in the schema.

User schema

To make querying a user by name fast, we can add an index to name. By default, only the _id field that MongoDB generates will be indexed. This means, to perform a search by name, the database will need to iterate over all the documents in the collection to find a matching name. When you add an index to name, you can query by name as quickly as when you query by _id. Now, when a user leaves, we can find the user by name directly and remove that user.

Also, we add the unique : true property to the index to avoid having multiple users with the same name, as shown in the following code:

var mongoose = require('mongoose'),
var schema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    index: {
      unique: true
    }
  }
});


var User = mongoose.model('user', schema);
module.exports = User;

User join

When a user joins a game, we create a user with the key name and save this user to MongoDB, as follows:

schema.statics.join = function(name, callback) {
  var user = new User({
    name: name
  });

  user.save(function(err, doc) {
    if (!callback) { return ; }
    if (err) { return callback(err); }

    callback(null, doc);
  });
};

The save() method in the preceding code uses callback patterns, which is also known as callback hell. If an error occurs, we make a call to the callback function passing the error as a parameter; otherwise, the operation succeeds and it returns the updated document.

The preceding callback pattern involves a lot of logic and condition checks. The nested callback pattern of JavaScript can quickly turn into a spaghetti nightmare. A good alternative is to use Promises to simplify things.

Mongoose's model.create() method (http://mongoosejs.com/docs/api.html#model_Model.create) can create and save a new document into the database if valid. Functions and documents such as objects and arrays are valid parameters for the model.create() method. The create method returns a Promise.

With this Promise, the caller of the join method can define the success and fail callbacks, simplifying the code:

schema.statics.join = function(name) {
  return User.create({
    name: name
  });
};
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.172.130