Skip to content

09 Express, Mongoose

Jagdeep Singh edited this page Jun 19, 2019 · 1 revision

Express

router.param(name, callback) middleware

Adds calback trigger to route parameters, where name is the name of the parameter.

Parameters of the callback function are:

  • req, the request object
  • res, the response object
  • next, indicating the next middleware function
  • The value of the name parameter
  • The name of the parameter

Does not accept array of route parameters like app.param()

Middleware (pre and post hooks) are functions which are passed control during execution of asynchronous functions.

Types of Middleware

  • Document

    this refers to the document.

  • Model

    this refers to the model

  • Aggregate

    for MyModel.aggregate()

    executes when you call exec() on an aggregate object

    this refers to the aggregation object

  • Query

    this refers to the query

Pre Hooks

All middleware types support pre and post hooks.

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

In mongoose 5.x, instead of calling next() manually, you can use a function that returns a promise, you can use async/await.

schema.pre('save', function() {
  return doStuff().then(() => doMoreStuff());
});

// or
schema.pre('save', async function() {
  await doStuff();
  await doMoreStuff();
});

Use Cases

Middleware are useful for atomizing model logic. Examples:

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

Errors in Pre Hooks

If any pre hook errors out, mongoose will not execute subsequent middleware or the hooked function. Instead it will pass an error to the callback and/or reject the returned promise.

Post Middleware

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 next() function.

Clone this wiki locally