Skip to content

Commit

Permalink
docs; clarify context for query middleware (Fix #2974)
Browse files Browse the repository at this point in the history
  • Loading branch information
vkarpov15 committed May 11, 2015
1 parent 9a6e206 commit 46c633a
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions docs/middleware.jade
Original file line number Diff line number Diff line change
Expand Up @@ -111,13 +111,30 @@ block content

:js
schema.pre('update', function() {
console.log(this instanceof mongoose.Query); // true
this.start = Date.now();
});

schema.post('update', function() {
console.log(this instanceof mongoose.Query); // true
console.log('update() took ' + (Date.now() - this.start) + ' millis');
});

:markdown
Query middleware differs from document middleware in a subtle but
important way: in document middleware, `this` refers to the document
being updated. In query middleware, mongoose doesn't necessarily have
a reference to the document being updated, so `this` refers to the
**query** object rather than the document being updated.

For instance, if you wanted to add an `updatedAt` timestamp to every
`update()` call, you would use the following pre hook.

:js
schema.pre('update', function() {
this.update({ $set: { updatedAt: Date.now() } });
});

h3#next Next Up
:markdown
Now that we've covered middleware, let's take a look at Mongoose's approach
Expand Down

0 comments on commit 46c633a

Please sign in to comment.