Started working on a existing project built using MEAN.IO, and Mongoose framework was used as well. I found its documentation a little confusing, so here’s what I found out after doing some research.

How to structure your model

Here’s a very simple example of how to structure a model.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var userSchema = new Schema({
name: {
type: String,
required: true,
trim: true
},
team: {
type: String,
required: true,
trim: true
}
});

userSchema.methods.testFunction = function(params, callback) {
// do something
}

userSchema.statics.defaultFunction= function(params, callback) {
// do something
}

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

###Difference between static and methods functions in Model

I got the following information from the Mongoose doc.

To put it simply, Method lets you replace the original .find() function with custom find query (equivalent of SELECT in SQL).

1
2
3
4
5
6
7
user
.myOwnFind()
.where(something)
.limit(20)
.exec(function (err, data) {
// etc
})

Statics are pretty much the same as methods but allow for defining functions that exist directly on your Model.

userSchema.statics.search = function(){} would overwrite default user.search(){}.

How to make calls your model from controller

Once the model is set up, it can then be called from controllers.

1
2
3
4
5
6
7
var User= require('../models/User');

Exports.create = function (params) {
User.testFunc(params, function(error, data) {
// do something
});
}