Skip to content

Commit

Permalink
docs(typescript): add notes about virtual context to Mongoose 6 migra…
Browse files Browse the repository at this point in the history
…tion and TypeScript virtuals docs

Fix #12806
  • Loading branch information
vkarpov15 committed Jan 16, 2023
1 parent a6fd84b commit a1b90e6
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
19 changes: 19 additions & 0 deletions docs/migrating_to_6.md
Original file line number Diff line number Diff line change
Expand Up @@ -511,3 +511,22 @@ The following legacy types have been removed:
* `HookDoneFunction`
* `SchemaTypeOpts`
* `ConnectionOptions`

Mongoose 6 infers the document's type for `this` in virtual getters and setters.
In Mongoose 5.x, `this` would be `any` in the following code.

```ts
schema.virtual('myVirtual').get(function() {
this; // any in Mongoose 5.x
});
```

In Mongoose 6, `this` will be set to the document type.

```ts
const schema = new Schema({ name: String });

schema.virtual('myVirtual').get(function() {
this.name; // string
});
```
16 changes: 16 additions & 0 deletions docs/typescript/virtuals.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,4 +82,20 @@ const schema = new Schema<UserDoc, UserModel, UserVirtuals>({ // <-- and here
schema.virtual('fullName').get(function() {
return `${this.firstName} ${this.lastName}`;
});
```

### Override the Type of `this` in Your Virtual

In case the value of `this` in your virtual is incorrect for some reason, you can always override it using the generic parameter to `virtual()`.

```ts
interface MyCustomUserDocumentType {
firstName: string;
lastName: string;
myMethod(): string;
}

schema.virtual<MyCustomUserDocumentType>('fullName').get(function() {
return this.method(); // returns string
});
```

0 comments on commit a1b90e6

Please sign in to comment.