Skip to content

Commit b9f2127

Browse files
authored
Merge pull request #12860 from Automattic/vkarpov15/gh-12684
docs(typescript): explain that virtuals inferred from schema only show up on Model, not raw document type
2 parents 426cc8c + c6b9b5f commit b9f2127

File tree

1 file changed

+28
-3
lines changed

1 file changed

+28
-3
lines changed

docs/typescript/virtuals.md

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,9 @@ const schema = new Schema(
1616
lastName: String,
1717
},
1818
{
19-
virtuals:{
20-
fullName:{
21-
get(){
19+
virtuals: {
20+
fullName: {
21+
get() {
2222
return `${this.firstName} ${this.lastName}`;
2323
}
2424
// virtual setter and options can be defined here as well.
@@ -28,7 +28,32 @@ const schema = new Schema(
2828
);
2929
```
3030

31+
Note that Mongoose does **not** include virtuals in the returned type from `InferSchemaType`.
32+
That is because `InferSchemaType` returns the "raw" document interface, which represents the structure of the data stored in MongoDB.
33+
34+
```ts
35+
type User = InferSchemaType<typeof schema>;
36+
37+
const user: User = {};
38+
// Property 'fullName' does not exist on type '{ firstName?: string | undefined; ... }'.
39+
user.fullName;
40+
```
41+
42+
However, Mongoose **does** add the virtuals to the model type.
43+
44+
```ts
45+
const UserModel = model('User', schema);
46+
47+
const user = new UserModel({ firstName: 'foo' });
48+
// Works
49+
user.fullName;
50+
51+
// Here's how to get the hydrated document type
52+
type UserDocument = ReturnType<(typeof UserModel)['hydrate']>;
53+
```
54+
3155
### Set virtuals type manually:
56+
3257
You shouldn't define virtuals in your TypeScript [document interface](../typescript.html).
3358
Instead, you should define a separate interface for your virtuals, and pass this interface to `Model` and `Schema`.
3459

0 commit comments

Comments
 (0)