-
Notifications
You must be signed in to change notification settings - Fork 0
09 Express, Mongoose
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.
-
Document
thisrefers to the document. -
Model
thisrefers to the model -
Aggregate
for
MyModel.aggregate()executes when you call
exec()on an aggregate objectthisrefers to the aggregation object -
Query
thisrefers to the query
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();
});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
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.
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 next() function.