Skip to content

Conversation

@arkist
Copy link
Contributor

@arkist arkist commented Nov 2, 2022

PR Checklist

Please check if your PR fulfills the following requirements:

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • Docs
  • Other... Please describe:

What is the current behavior?

Currently, techniques/mongodb doc uses intersection type for defining the mongoose document interface.

import { Document } from 'mongoose';

export type CatDocument = Cat & Document;

it was okay before [email protected] but after that, they replaced the use of this with generics(T) in many Document methods so it infers incorrectly now.

// before
toObject(options?: ToObjectOptions): LeanDocument<this>;
toObject<T = DocType>(options?: ToObjectOptions): T;

// latest
toObject<T = LeanDocument<DocType>>(options?: ToObjectOptions): Require_id<T>;

// from: https://github.com/Automattic/mongoose/commit/659436de47d55aaa0a984b8f4cc99232c5ca8a16
type CatDocument = Cat & Document;

class CatsService {
  constructor(@InjectModel(Cat.name) private catModel: Model<CatDocument>) {}

  create() {
    const cat = await this.catModel.create(createCatDto);
    const catObj = cat.toObject();
    // const catObj: LeanDocument<any> & Required<{_id: unknown}>

    return catObj;
  }
}

What is the new behavior?

Mongoose introduced HydratedDocument from 6.0.13.

import { HydratedDocument } from 'mongoose';

export type CatDocument = HydratedDocument<Cat>;

defining document interface as HydratedDocument of Cat so can infer the type from Document methods correctly.

type CatDocument = HydratedDocument<Cat>;

class CatsService {
  constructor(@InjectModel(Cat.name) private catModel: Model<CatDocument>) {}

  create() {
    const cat = await this.catModel.create(createCatDto);
    const catObj = cat.toObject();
    // const catObj: LeanDocument<Cat> & {_id: Types.ObjectId}

    return catObj;
  }
}

refs:
Automattic/mongoose@8120c8f
https://github.com/Automattic/mongoose/blob/6.7.0/docs/typescript.md#creating-your-first-document

Does this PR introduce a breaking change?

  • Yes
  • No

@kamilmysliwiec
Copy link
Member

Would you like to create a PR updating the corresponding sample in the nestjs/nest repository? https://github.com/nestjs/nest/blob/master/sample/06-mongoose/src/cats/schemas/cat.schema.ts

@arkist
Copy link
Contributor Author

arkist commented Nov 2, 2022

@kamilmysliwiec sure 😄 👉🏻 nestjs/nest#10505

@kamilmysliwiec kamilmysliwiec merged commit 9675a31 into nestjs:master Nov 3, 2022
@kamilmysliwiec
Copy link
Member

lgtm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants