Skip to content

Commit 1e652c6

Browse files
committed
docs(typescript): clarify that setting THydratedDocumentType on schemas is necessary for correct method context
Fix #14573
1 parent 88afc33 commit 1e652c6

File tree

1 file changed

+19
-4
lines changed

1 file changed

+19
-4
lines changed

docs/typescript/schemas.md

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,7 @@ This is because Mongoose has numerous features that add paths to your schema tha
164164
## Arrays
165165

166166
When you define an array in a document interface, we recommend using vanilla JavaScript arrays, **not** Mongoose's `Types.Array` type or `Types.DocumentArray` type.
167-
Instead, use the `THydratedDocumentType` generic to define that the hydrated document type has paths of type `Types.Array` and `Types.DocumentArray`.
167+
Instead, use the `THydratedDocumentType` generic for models and schemas to define that the hydrated document type has paths of type `Types.Array` and `Types.DocumentArray`.
168168

169169
```typescript
170170
import mongoose from 'mongoose'
@@ -178,17 +178,27 @@ interface IOrder {
178178
// for fully hydrated docs returned from `findOne()`, etc.
179179
type OrderHydratedDocument = mongoose.HydratedDocument<
180180
IOrder,
181-
{ tags: mongoose.Types.DocumentArray<{ name: string }> }
181+
{ tags: mongoose.HydratedArraySubdocument<{ name: string }> }
182182
>;
183183
type OrderModelType = mongoose.Model<
184184
IOrder,
185185
{},
186186
{},
187187
{},
188-
OrderHydratedDocument
188+
OrderHydratedDocument // THydratedDocumentType
189189
>;
190190

191-
const orderSchema = new mongoose.Schema<IOrder, OrderModelType>({
191+
const orderSchema = new mongoose.Schema<
192+
IOrder,
193+
OrderModelType,
194+
{}, // methods
195+
{}, // query helpers
196+
{}, // virtuals
197+
{}, // statics
198+
mongoose.DefaultSchemaOptions, // schema options
199+
IOrder, // doctype
200+
OrderHydratedDocument // THydratedDocumentType
201+
>({
192202
tags: [{ name: { type: String, required: true } }]
193203
});
194204
const OrderModel = mongoose.model<IOrder, OrderModelType>('Order', orderSchema);
@@ -207,3 +217,8 @@ async function run() {
207217
leanDoc.tags; // Array<{ name: string }>
208218
};
209219
```
220+
221+
Use `HydratedArraySubdocument<RawDocType>` for the type of array subdocuments, and `HydratedSingleSubdocument<RawDocType>` for single subdocuments.
222+
223+
If you are not using [schema methods](../guide.html#methods) or [virtuals](../tutorials/virtuals.html), you can omit the last 7 generic parameters to `Schema()` and just define your schema using `new mongoose.Schema<IOrder, OrderModelType>(...)`.
224+
The THydratedDocumentType parameter for schemas is primarily for setting the value of `this` on methods and virtuals.

0 commit comments

Comments
 (0)