Default function - set the default schema option to a function and use the return value as the default.
Getters and Setters
Getters and setters could change attributes defined by the keys and values in the document.
Setter: transform data before it is stored mongodb.
Getter: transform the representation of the data when retreive from mongodb.
Another example about getter:
Validation
Like in html, available validations are:
for type: Number
required: true/false
max: Number
min: Number
for type: String
required: true/false
enum: [A, B, C]
match: regexp
maxlength: Number
minlength: Number
We could also customize a validation:
validate: function(){} - customized validation. Must return true/false
Methods
Each Schema can define instance and static methods for its model.
Define instance method - SchemaName.methods.functionName = function functionName () {};
Define static method - SchemaName.statics.functionName = function functionName () {};
Middleware
Middleware (also called pre and post hooks) are functions which are passed control during execution of asynchronous functions. Mongoose has 2 types of middleware:
There is no query hook for remove(), only for documents. If we set a ‘remove’ hook, it will be fired when you call myDoc.remove(), not when we call MyModel.remove().
Pre and Post
Two types of pre hooks:
Serial - Serial middleware are executed one after another, when each middleware calls next.
Parallel - Parallel middleware are executed in parallel.
Post middleware are executed after the hooked method and all of its pre middleware have completed. Two types of post hooks:
Common post hook does not directly receive flow control, e.g. no next or done callbacks are passed to it. it is used in a way to register traditional event listeners for these methods.
Asynchronous Post Hooks - they are executed in a pre-defined order. If post hook function takes at least 2 parameters (function(doc, next)), mongoose will assume the second parameter is a next() function that we will call to trigger the next middleware in the sequence.
When we put common post hook with asynchronous post hook together. Common post hook will be triggered firstly!
Error handling
If any middleware calls next or done with a parameter of type Error, the flow is interrupted, and the error is passed to the callback.
Virtual attributes
Virtual attributes are attributes that are convenient to have around but that do not get persisted to mongodb. For example, we persist firstName and lastName, but we also prefer to have fullName. Then virtual attribute could be a good choice!
We must set toJSON/toObject to be able to output it!