Description
Prerequisites
- I have written a descriptive issue title
- 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):
function isPopulated<T, S extends mongoose.RefType>(
doc: mongoose.PopulatedDoc<T, S>
): doc is T extends mongoose.HydratedDocument<infer T1, infer T2, infer T3> ? mongoose.HydratedDocument<T1, T2, T3> : T extends object ? DocumentType<T> : 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.
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.