Skip to content

API User 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 user model. The user schema is very simple, we don't need a lot of information. We will first define which elements we need, and then show you how to define them into Mongoose.


Define the schema

Composition of a user:

  • Username
    • Type: String, Required, index: unique
  • Password
    • Type: String, Required
  • Mail
    • Type: String, Required, index: unique
  • IsEmailVisible
    • Type: Boolean, default: false

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

var Schema = mongoose.Schema;

var UserSchema = new Schema({
	username		: { type: String, required: true, index: {unique: true} },
	password		: { type: String, required: true },
	mail			: { type: String, required: true, index: {unique: true} },
	isEmailVisible	: { type: Boolean, default: false}
});

As you probably noticed, we added some restrictions to our schema (required, default values, type, index, 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.
Furthermore, index: {unique:true} is very important to restrict the creation of accounts.
We do not allow twice same e-mail or username in the database.


Model & Export

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

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