-
Notifications
You must be signed in to change notification settings - Fork 18
Class 09 API Server
express router.param() middleware - this link takes you to the middleware implementation section of the express server documentation.
mongoose middleware - Good descriptions of the different types of middleware and their query types. There is also a section on error middleware
Middleware (also called pre and post hooks) are functions which are passed control during execution of asynchronous functions. Middleware is specified on the schema level and is useful for writing plugins.
Mongoose has 4 types of middleware: document middleware, model middleware, aggregate middleware, and query middleware. All middleware types support pre and post hooks. How pre and post hooks work is described in more detail below.
Supported for the following document functions. In document middleware functions, this
refers to the document.
- validate
- save
- remove
- init (note: init hooks are synchronous)
In query middleware functions, this
refers to the query.
- count
- deleteMany
- deleteOne
- find
- findOne
- findOneAndDelete
- findOneAndRemove
- findOneAndUpdate
- remove
- update
- updateOne
- updateMany
Aggregate middleware is for MyModel.aggregate(). Aggregate middleware executes when you call exec() on an aggregate object. In aggregate middleware, this refers to the aggregation object.
- aggregate
Model middleware is supported for the following model functions. In model middleware functions, this refers to the model.
- insertMany
Pre middleware functions are executed one after another, when each middleware calls next.
- complex validation
- removing dependent documents (removing a user removes all his blogposts)
- asynchronous defaults
- asynchronous tasks that a certain action triggers
post middleware are executed after the hooked method and all of its pre middleware have completed.
If your post hook function takes at least 2 parameters, mongoose will assume the second parameter is a next() function that you will call to trigger the next middleware in the sequence.