Skip to content

Class 09 API Server

Erin Trainor edited this page Mar 27, 2019 · 2 revisions

Resources

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

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.

Types of Middleware

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.

Document middleware

Supported for the following document functions. In document middleware functions, this refers to the document.

  • validate
  • save
  • remove
  • init (note: init hooks are synchronous)

Query Middleware

In query middleware functions, this refers to the query.

  • count
  • deleteMany
  • deleteOne
  • find
  • findOne
  • findOneAndDelete
  • findOneAndRemove
  • findOneAndUpdate
  • remove
  • update
  • updateOne
  • updateMany

Aggregate Middleware

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

Model middleware is supported for the following model functions. In model middleware functions, this refers to the model.

  • insertMany

What are pre and post hooks?

Pre hook

Pre middleware functions are executed one after another, when each middleware calls next.

Use Cases

  • complex validation
  • removing dependent documents (removing a user removes all his blogposts)
  • asynchronous defaults
  • asynchronous tasks that a certain action triggers

Post hook

post middleware are executed after the hooked method and all of its pre middleware have completed.

Asynchronous Post Hooks

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.

Clone this wiki locally