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 = this.word.length;
  next();
});

There are two types of middleware functions—the pre and post functions—and they are handled a bit differently. The pre functions receive a next parameter, which is the next middleware function to execute. The pre functions can be called asynchronously or synchronously. In the case of the asynchronous method, an additional done parameter is passed to the pre function so you can notify the asynchronous framework that you are finished. If you are applying operations that should be done in order in the middleware, you should use the synchronous method.

To apply the middleware synchronously, you simply call next() in the middleware function. For example:

shchema.pre('save', function(next)){
  next();
});

To apply the middleware asynchronously, add a true parameter to the pre() method to denote asynchronous behavior and then call doAsyn(done) inside the middleware function. For example:

shchema.pre('save', true, function(next, done)){
  next();
  doAsync(done);
});

You call the post middleware functions after the init, validate, save, or remove operation has been processed. This allows you to do any cleanup work necessary when applying the operation. For example, the following implements a simple post save method which logs that the object has been saved:

schema.post('save', function(doc){
  console.log("Document Saved: " + doc.toString());
});

Listing 16.12 illustrates the process of implementing middleware for each stage of the document life cycle. Notice that the validate and save middleware functions are executed when saving the document. You execute the init middleware functions when retrieving the document from MongoDB by using findOne(). You execute the remove middleware functions when using remove() to delete a document from MongoDB.

Also notice that you can use the this keyword in all the middleware functions except pre init to access the Document object. In the case of pre init, you do not yet have a document from the database to use. Figure 16.12 shows the output of the code in Listing 16.12.

Listing 16.12 mongoose_middleware.js: Applying a middleware framework to a model by using Mongoose


01 var mongoose = require('mongoose'),
02 var db = mongoose.connect('mongodb://localhost/words'),
03 var wordSchema = require('./word_schema.js').wordSchema;
04 var Words = mongoose.model('Words', wordSchema);
05 Words.schema.pre('init', function (next) {
06   console.log('a new word is about to be initialized from the db'),
07   next();
08 });
09 Words.schema.pre('validate', function (next) {
10   console.log('%s is about to be validated', this.word);
11   next();
12 });
13 Words.schema.pre('save', function (next) {
14   console.log('%s is about to be saved', this.word);
15   console.log('Setting size to %d', this.word.length);
16   this.size = this.word.length;
17   next();
18 });
19 Words.schema.pre('remove', function (next) {
20   console.log('%s is about to be removed', this.word);
21   next();
22 });
23 Words.schema.post('init', function (doc) {
24   console.log('%s has been initialized from the db', doc.word);
25 });
26 Words.schema.post('validate', function (doc) {
27   console.log('%s has been validated', doc.word);
28 });
29 Words.schema.post('save', function (doc) {
30   console.log('%s has been saved', doc.word);
31 });
32 Words.schema.post('remove', function (doc) {
33   console.log('%s has been removed', doc.word);
34 });
35 mongoose.connection.once('open', function(){
36   var newWord = new Words({
37     word:'newword',
38     first:'t',
39     last:'d',
40     size:'newword'.length,
41   });
42   console.log(" Saving: ");
43   newWord.save(function (err){
44     console.log(" Finding: ");
45     Words.findOne({word:'newword'}, function(err, doc){
46       console.log(" Removing: ");
47       newWord.remove(function(err){
48         mongoose.disconnect();
49       });
50     });
51   });
52 });


Image

Figure 16.12 Applying a middleware framework to a model by using Mongoose.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.239.105