Skip to content

When the _id field is specified in the schema definition, the type of _id field cannot be correctly inferred in the HydratedDocument, perhaps due to incorrect implemention of Require_id #12070

@Starrah

Description

@Starrah

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Mongoose version

6.4.3

Node.js version

16.15.1

MongoDB server version

This issue have no relevance to MongoDB server.

Description

When the _id field is specified in the schema definition, eg, new Schema({_id: String}), the type of _id field cannot be correctly inferred in the HydratedDocument (the type returned by new Model or await Model.findOne).

Please see the "Steps to Reproduce" section for reproducing code.

I think that the bug is perhaps due to incorrect implemention of Require_id:

mongoose/types/index.d.ts

Lines 111 to 115 in 3445d24

export type Require_id<T> = T extends { _id?: infer U }
? U extends any
? (T & { _id: Types.ObjectId })
: T & Required<{ _id: U }>
: T & { _id: Types.ObjectId };
.

Sorry that I'm not excellent in Typescript, but what does U extends any here mean?
As far as I know, everything extends any? so the contiditional clause (T & { _id: Types.ObjectId }) is always used, and the clause T & Required<{ _id: U }> is never used.

Thus, _id will be always infered with type ObjectId, even if I have defined another type such as String in the Schema definition.

The issue have been previously discussed at e0d299f#r915551078 with @mohammad0-0ahmad @Uzlopak, please see the link for details.

Steps to Reproduce

The following test case demonstrates the bug:

// index.test-d.ts
import {model, Schema} from "mongoose";
import {expectType} from "tsd";

const schema_with_string_id = new Schema({_id: String, nickname: String})
const theModel = model('test', schema_with_string_id)
const obj = new theModel()

expectType<string>(obj._id)

when testing it with tsd, gives the following error:

 index.test-d.ts:8:0
  ✖  8:0  Parameter type string is declared too wide for argument type string & ObjectId.

Expected Behavior

No response

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