You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/typescript/virtuals.md
+28Lines changed: 28 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,6 +1,34 @@
1
1
# Virtuals in TypeScript
2
2
3
3
[Virtuals](/docs/tutorials/virtuals.html) are computed properties: you can access virtuals on hydrated Mongoose documents, but virtuals are **not** stored in MongoDB.
4
+
Mongoose supports auto typed virtuals so you don't need to define additional typescript interface anymore but you are still able to do so.
5
+
6
+
### Automatically Inferred Types:
7
+
8
+
To make mongoose able to infer virtuals type, You have to define them in schema constructor as following:
9
+
10
+
```ts
11
+
import { Schema, Model, model } from'mongoose';
12
+
13
+
const schema =newSchema(
14
+
{
15
+
firstName: String,
16
+
lastName: String,
17
+
},
18
+
{
19
+
virtuals:{
20
+
fullName:{
21
+
get(){
22
+
return`${this.firstName} ${this.lastName}`;
23
+
}
24
+
// virtual setter and options can be defined here as well.
25
+
}
26
+
}
27
+
}
28
+
);
29
+
```
30
+
31
+
### Set virtuals type manually:
4
32
You shouldn't define virtuals in your TypeScript [document interface](/docs/typescript.html).
5
33
Instead, you should define a separate interface for your virtuals, and pass this interface to `Model` and `Schema`.
0 commit comments