Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs(typescript): recommend using HydratedSingleSubdocument over Types.Subdocument #15240

Merged
merged 1 commit into from
Feb 8, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion docs/typescript/subdocuments.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,11 @@ Define a separate `THydratedDocumentType` and pass it as the 5th generic param t
`THydratedDocumentType` controls what type Mongoose uses for "hydrated documents", that is, what `await UserModel.findOne()`, `UserModel.hydrate()`, and `new UserModel()` return.

```ts
import { HydratedSingleSubdocument } from 'mongoose';

// Define property overrides for hydrated documents
type THydratedUserDocument = {
names?: mongoose.Types.Subdocument<Names>
names?: HydratedSingleSubdocument<Names>
}
type UserModelType = mongoose.Model<User, {}, {}, {}, THydratedUserDocument>;

Expand All @@ -51,6 +53,7 @@ const UserModel = mongoose.model<User, UserModelType>('User', userSchema);

const doc = new UserModel({ names: { _id: '0'.repeat(24), firstName: 'foo' } });
doc.names!.ownerDocument(); // Works, `names` is a subdocument!
doc.names!.firstName; // 'foo'
```

## Subdocument Arrays
Expand Down Expand Up @@ -81,4 +84,5 @@ const UserModel = model<User, UserModelType>('User', new Schema<User, UserModelT

const doc = new UserModel({});
doc.names[0].ownerDocument(); // Works!
doc.names[0].firstName; // string
```