types(models): default _id type to ObjectId for Document #15688
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
This pull request changes the default generic type
Tfor theDocumentclass fromunknowntoObjectId.The motivation for this change is to improve the developer experience for TypeScript users by providing a more practical and intuitive default. In the vast majority of Mongoose schemas, the
_idfield is anObjectIdby default. Aligning the generic typeT(which represents the type of_id) with this behavior reduces boilerplate and prevents potential type errors.Currently, developers often have to explicitly define
Document<ObjectId>to get proper type-safety on the_idfield. By makingObjectIdthe default, the types will work out-of-the-box for the most common use case.This also raises a question: I'm curious about the original rationale for choosing
unknownas the default. There may be a design consideration I am not aware of, and understanding it would be valuable.Examples
This change directly impacts type inference on document instances.
Current Behavior
With the default
T = unknown, accessing methods on_idwithout explicit typing results in a TypeScript error.After this PR
With the default
T = ObjectId, the_idproperty is correctly typed, and no errors occur.