1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
Middleware
==========
Middleware are defined at the Schema level and are applied when the methods
`init` (when a document is initialized with data from MongoDB), `save`, and
`remove` are called on a document instance.
There are two types of middleware, serial and parallel.
Serial middleware are defined like:
schema.pre('save', function (next) {
// ...
})
They're executed one after the other, when each middleware calls `next`.
Parallel middleware offer more fine-grained flow control, and are defined
like
schema.pre('remove', true, function (next, done) {
// ...
})
Parallel middleware can `next()` immediately, but the final argument will be
called when all the parallel middleware have called `done()`.
## Use cases
Middleware are useful for:
- Complex validation
- Removing dependent documents when a certain document is removed (eg:
removing a user removes all his blogposts)
- Asynchronous defaults
- Asynchronous tasks that a certain action triggers. For example:
- Triggering custom events
- Creating notifications
- Emails
and many other things. They're specially useful for atomizing model logic
and avoiding nested blocks of async code.
## Error handling
If any middleware calls `next` or `done` with an `Error` instance, the flow is
interrupted, and the error is passed to the callback.
For example:
schema.pre('save', function (next) {
// something goes wrong
next(new Error('something went wrong'));
});
// later...
myModel.save(function (err) {
// err can come from a middleware
});
|