Skip to content

Why is the default type of the generic field _id in the class Document of type "any"? #14520

@a1rwulf

Description

@a1rwulf

Prerequisites

  • I have written a descriptive issue title

Mongoose version

8.3.1

Node.js version

20.12.1

MongoDB version

6.0

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

14.2.1 (23C71)

Issue

I just fell victim to an issue similar to:
#11085

Which was caused by legacy code we've been using in NestJS:
nestjs/docs.nestjs.com#2517

After researching this for quite some time, I undersand we are supposed to use the HydratedDocument these days, but I'd still be nice if somebody can shade some light into why it is what it is at the moment.

So here is my example:
Our schemas are defined like this (which is how it was found in NestJS docs, a few years ago):

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import { Types } from 'mongoose';

@Schema()
export class Cat {
  _id: Types.ObjectId;

  @Prop()
  name: string;

  @Prop()
  age: number;

  @Prop()
  breed: string;
}

export type CatDocument = Cat & Document;
export const CatSchema = SchemaFactory.createForClass(Cat);

The interesting part is here is:
export type CatDocument = Cat & Document;

Which basically makes _id be of type any instead of Types.ObjectId.
As per above issue, I wonder why document is defined as class Document<T = any, TQueryHelpers = any, DocType = any> in https://github.com/Automattic/mongoose/blob/master/types/document.d.ts#L19 while the HydratedDocument was changed to use unknown to circumvent the problem with any inference.

Wouldn't it make sense to either use unkown or class Document<T = Types.ObjectId, TQueryHelpers = any, DocType = any> to default to ObjectId and leave the user a way to use any instead?

Thanks for any answers to this question.

Metadata

Metadata

Assignees

No one assigned

    Labels

    typescriptTypes or Types-test related issue / Pull Request

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions