Skip to content

Add Typeguard for Populated documents, or at least note that it is possible in the populate guide #12664

Open
@hasezoey

Description

@hasezoey

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    docsThis issue is due to a mistake or omission in the mongoosejs.com documentationenhancementThis issue is a user-facing general improvement that doesn't fix a bug or add a new featuretypescriptTypes or Types-test related issue / Pull Request

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions