O'Reilly logo

Node.js, MongoDB, and AngularJS Web Development by Brad Dayley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Implementing Middleware Functions

Mongoose provides a middleware framework where pre and post functions are called before and after the init(), validate(), save(), and remove() methods on a Document object. A middleware framework allows you to implement functionality that should be applied before or after a specific step in a process. For example, when creating word documents using the model defined earlier in this chapter, you might want to automatically set the size to the length of the word field, as shown in the following pre() save() middleware function:

Words.schema.pre('save', function (next) {  console.log('%s is about to be saved', this.word);  console.log('Setting size to %d', this.word.length);  this.size ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required