diff --git a/docs/migrating_to_6.md b/docs/migrating_to_6.md index 5b9245d856c..d7b97ba6dad 100644 --- a/docs/migrating_to_6.md +++ b/docs/migrating_to_6.md @@ -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 +}); +``` diff --git a/docs/typescript/virtuals.md b/docs/typescript/virtuals.md index dda7cd729fe..5969d229e85 100644 --- a/docs/typescript/virtuals.md +++ b/docs/typescript/virtuals.md @@ -82,4 +82,20 @@ const schema = new Schema({ // <-- 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('fullName').get(function() { + return this.method(); // returns string +}); ``` \ No newline at end of file