Skip to content

Commit a1b90e6

Browse files
committed
docs(typescript): add notes about virtual context to Mongoose 6 migration and TypeScript virtuals docs
Fix #12806
1 parent a6fd84b commit a1b90e6

2 files changed

Lines changed: 35 additions & 0 deletions

File tree

docs/migrating_to_6.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -511,3 +511,22 @@ The following legacy types have been removed:
511511
* `HookDoneFunction`
512512
* `SchemaTypeOpts`
513513
* `ConnectionOptions`
514+
515+
Mongoose 6 infers the document's type for `this` in virtual getters and setters.
516+
In Mongoose 5.x, `this` would be `any` in the following code.
517+
518+
```ts
519+
schema.virtual('myVirtual').get(function() {
520+
this; // any in Mongoose 5.x
521+
});
522+
```
523+
524+
In Mongoose 6, `this` will be set to the document type.
525+
526+
```ts
527+
const schema = new Schema({ name: String });
528+
529+
schema.virtual('myVirtual').get(function() {
530+
this.name; // string
531+
});
532+
```

docs/typescript/virtuals.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,4 +82,20 @@ const schema = new Schema<UserDoc, UserModel, UserVirtuals>({ // <-- and here
8282
schema.virtual('fullName').get(function() {
8383
return `${this.firstName} ${this.lastName}`;
8484
});
85+
```
86+
87+
### Override the Type of `this` in Your Virtual
88+
89+
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()`.
90+
91+
```ts
92+
interface MyCustomUserDocumentType {
93+
firstName: string;
94+
lastName: string;
95+
myMethod(): string;
96+
}
97+
98+
schema.virtual<MyCustomUserDocumentType>('fullName').get(function() {
99+
return this.method(); // returns string
100+
});
85101
```

0 commit comments

Comments
 (0)