Mongoose Middleware - mwilkin-401-advanced-javascript/bend-javascript-401d2 GitHub Wiki

Mongoose is JavaScript library that enables interaction with MongoDB and Node.js. It manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB.

Mongoose has middleware which are also called pre and post hooks because they are functions that can interact with the data going in and out of the persistence layer.

Importantly, the order in which the hooks are utilized matters and mongoose has a lot of pre-built in functions that make the job of the developer easier. In addition to the pre-built functions, customized functions can be created to fulfill needs and requirements as necessary.

There are 4 types of Middleware in mongoose: 1. Document, 2. Model, 3. Aggregate, and 4. Query. Notably, in document middleware functions, this refers to the document. With Query middleware, this refers to the query. With Aggregate middleware, this refers to the aggregation object and executes when exec() is called. This, in Model middleware, refers to the model.

Middleware can be used for complex validation, like access validation, removing dependent documents, asynchronous defaults, and asynchronous task that are triggered by a certain action.

If an error is encountered while a pre-hook is running (or if the pre hook errors out), all subsequent middleware will not run and an error will pass an error and/or reject the returned promise.

Mongoose middleware is a powerful feature that adds functionality and simplifies implementation.