Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add documentation for calling schema.post() with async function #14514

Merged
merged 3 commits into from Apr 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
25 changes: 21 additions & 4 deletions docs/middleware.md
Expand Up @@ -151,7 +151,7 @@ schema.pre('save', function() {
then(() => doMoreStuff());
});

// Or, in Node.js >= 7.6.0:
// Or, using async functions
schema.pre('save', async function() {
await doStuff();
await doMoreStuff();
Expand Down Expand Up @@ -250,9 +250,7 @@ schema.post('deleteOne', function(doc) {

<h2 id="post-async"><a href="#post-async">Asynchronous Post Hooks</a></h2>

If your post hook function takes at least 2 parameters, mongoose will
assume the second parameter is a `next()` function that you will call to
trigger the next middleware in the sequence.
If your post hook function takes at least 2 parameters, mongoose will assume the second parameter is a `next()` function that you will call to trigger the next middleware in the sequence.

```javascript
// Takes 2 parameters: this is an asynchronous post hook
Expand All @@ -271,6 +269,25 @@ schema.post('save', function(doc, next) {
});
```

You can also pass an async function to `post()`.
If you pass an async function that takes at least 2 parameters, you are still responsible for calling `next()`.
However, you can also pass in an async function that takes less than 2 parameters, and Mongoose will wait for the promise to resolve.

```javascript
schema.post('save', async function(doc) {
await new Promise(resolve => setTimeout(resolve, 1000));
console.log('post1');
// If less than 2 parameters, no need to call `next()`
});

schema.post('save', async function(doc, next) {
await new Promise(resolve => setTimeout(resolve, 1000));
console.log('post1');
// If there's a `next` parameter, you need to call `next()`.
next();
});
```

<h2 id="defining"><a href="#defining">Define Middleware Before Compiling Models</a></h2>

Calling `pre()` or `post()` after [compiling a model](models.html#compiling)
Expand Down
4 changes: 4 additions & 0 deletions test/types/middleware.test.ts
Expand Up @@ -63,6 +63,10 @@ schema.post<ITest>('save', function() {
console.log(this.name);
});

schema.post<ITest>('save', async function() {
console.log(this.name);
});

schema.post<ITest>('save', function(err: Error, res: ITest, next: Function) {
console.log(this.name, err.stack);
});
Expand Down