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 ...
Get Node.js, MongoDB, and AngularJS Web Development now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.