Skip to content

API Vote Model

Romain Francois edited this page Dec 19, 2016 · 1 revision

Prerequisites & Configuration

We need to requires some libraries in order to set the Info model for MongoDB. (using mongoose).

var mongoose = require('mongoose');
var Promise  = require('bluebird');
	
Promise.promisifyAll(mongoose);
  • Mongoose used to define the schema and the model.

  • Bluebird to manipulate Promise (already built in Express but deprecated). We define bluebird as the default Promise feature with the following lines:

      mongoose.Promise = require('bluebird');
      Promise.promisifyAll(mongoose);
    

So now, we have everything to build the vote model. The vote schema is the simplest one we have to do. We will first define which elements we need, and then show you how to define them into Mongoose.


Define the schema

Composition of a vote:

  • UserID
    • Type: String, Required
  • Value
    • Type: Number, Required, default: 0

So to define our schema using mongoose, we have to write this:

var Schema = mongoose.Schema;

var schema = new Schema({
	userID 		: { type: String, required: true },
	value		: { type: Number, required: true, default: 0}
});

As you probably noticed, we added some restrictions to our schema (required, default values, type, etc..). This is to force a good usage for the data stockage. If one of these restrictions is not respected, mongoose will emit an error and won't perform any action.


Model & Export

Finally we defined the model and export it in order to use it in other files.

var model = mongoose.model('Vote', schema);

module.exports = {
	model,
	schema
};