Skip to content

Commit

Permalink
docs(typescript): explain that virtuals inferred from schema only sho…
Browse files Browse the repository at this point in the history
…w up on Model, not raw document type

Fix #12684
  • Loading branch information
vkarpov15 committed Jan 2, 2023
1 parent 2aee7c1 commit c6b9b5f
Showing 1 changed file with 28 additions and 3 deletions.
31 changes: 28 additions & 3 deletions docs/typescript/virtuals.md
Expand Up @@ -16,9 +16,9 @@ const schema = new Schema(
lastName: String,
},
{
virtuals:{
fullName:{
get(){
virtuals: {
fullName: {
get() {
return `${this.firstName} ${this.lastName}`;
}
// virtual setter and options can be defined here as well.
Expand All @@ -28,7 +28,32 @@ const schema = new Schema(
);
```

Note that Mongoose does **not** include virtuals in the returned type from `InferSchemaType`.
That is because `InferSchemaType` returns the "raw" document interface, which represents the structure of the data stored in MongoDB.

```ts
type User = InferSchemaType<typeof schema>;

const user: User = {};
// Property 'fullName' does not exist on type '{ firstName?: string | undefined; ... }'.
user.fullName;
```

However, Mongoose **does** add the virtuals to the model type.

```ts
const UserModel = model('User', schema);

const user = new UserModel({ firstName: 'foo' });
// Works
user.fullName;

// Here's how to get the hydrated document type
type UserDocument = ReturnType<(typeof UserModel)['hydrate']>;
```

### Set virtuals type manually:

You shouldn't define virtuals in your TypeScript [document interface](../typescript.html).
Instead, you should define a separate interface for your virtuals, and pass this interface to `Model` and `Schema`.

Expand Down

0 comments on commit c6b9b5f

Please sign in to comment.