You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Pre middleware functions are executed one after another, when each
132
-
middleware calls `next`.
131
+
Pre middleware functions are executed one after another.
133
132
134
133
```javascript
135
134
constschema=newSchema({ /* ... */ });
136
-
schema.pre('save', function(next) {
135
+
schema.pre('save', function() {
137
136
// do stuff
138
-
next();
139
137
});
140
138
```
141
139
142
-
In [mongoose 5.x](http://thecodebarbarian.com/introducing-mongoose-5.html#promises-and-async-await-with-middleware), instead of calling `next()` manually, you can use a
143
-
function that returns a promise. In particular, you can use [`async/await`](http://thecodebarbarian.com/common-async-await-design-patterns-in-node.js.html).
140
+
You can also use a function that returns a promise, including async functions.
141
+
Mongoose will wait until the promise resolves to move on to the next middleware.
For document middleware, like `pre('save')`, Mongoose passes the 1st parameter to `save()` as the 2nd argument to your `pre('save')`callback.
377
-
You should use the 2nd argument to get access to the `save()` call's `options`, because Mongoose documents don't store all the options you can pass to `save()`.
358
+
Mongoose also passes the 1st parameter to the hooked function, like `save()`, as the 1st argument to your `pre('save')`function.
359
+
You should use the argument to get access to the `save()` call's `options`, because Mongoose documents don't store all the options you can pass to `save()`.
## In `isAsync` middleware `next()` errors take priority over `done()` errors
188
+
## `isAsync` middleware no longer supported
189
189
190
-
Due to Mongoose middleware now relying on promises and async/await, `next()` errors take priority over `done()` errors.
191
-
If you use `isAsync` middleware, any errors in `next()` will be thrown first, and `done()` errors will only be thrown if there are no `next()` errors.
190
+
Mongoose 9 no longer supports `isAsync` middleware. Middleware functions that use the legacy signature with both `next` and `done` callbacks (i.e., `function(next, done)`) are not supported. We recommend middleware now use promises or async/await.
191
+
192
+
If you have code that uses `isAsync` middleware, you must refactor it to use async functions or return a promise instead.
0 commit comments