Automattic / Automattic/mongoose
Add Typeguard for Populated documents, or at least note that it is possible in the populate guide
- Dominant language
- JavaScript
- Stars
- 27.5k
- Forks
- 4k
- Avg merge
- 2d 7h
- Merged PRs (30d)
- 35
Description
### Prerequisites
- [X] I have written a descriptive issue title
- [X] I have searched existing issues to ensure the issue has not already been raised
### Issue
This issue is a proposal to add a official `isPopulated(doc.path)` function to act as a typeguard both for types and in runtime.
A typeguard in typescript asserts that a input type is a specific type, and the same (or at least close to it) at runtime, for example (how typegoose does it):
```ts
function isPopulated(
doc: mongoose.PopulatedDoc
): doc is T extends mongoose.HydratedDocument ? mongoose.HydratedDocument : T extends object ? DocumentType : never {
return doc instanceof mongoose.Model;
}
```
Note: the typeguard above is a modified version from typegoose and the types have been changed to similar types in mongoose, but has not been tested, so it is just pseudo-code.
Also read [Typescript Narrowing: Using type predicates](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates).
Maybe a opposite function to check if the input is the ref type (ie unpopulated) would be a good idea; but from what i know it would not be just a simple invert of `isPopulated`.
If such a function is not added to mongoose itself, it should be noted in `docs/typescript/populate.html` that it is possible to outsource the check to a function while having the types still work.
Contributor guide
Research direction
Start by reading docs/typescript/populate.html and the TypeScript narrowing guidance linked in the issue. Decide whether the scope is a Mongoose runtime/typeguard API or documentation of an external check; done means the selected behavior is implemented and documented with compatible types and runtime behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript, typescript
- Domain
- backend-api-design, documentation
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Quiet
- Clarity
- Needs clarification
- Newbie friendliness
- 42/100