How to create models in Mongoose

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.

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).

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.

var User= require('../models/User');

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