File tree Expand file tree Collapse file tree 1 file changed +28
-3
lines changed Expand file tree Collapse file tree 1 file changed +28
-3
lines changed Original file line number Diff line number Diff 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+
3257You shouldn't define virtuals in your TypeScript [ document interface] ( ../typescript.html ) .
3358Instead, you should define a separate interface for your virtuals, and pass this interface to ` Model ` and ` Schema ` .
3459
You can’t perform that action at this time.
0 commit comments