From b59cbed0e9e49d7799795fc395bf135946b2bd20 Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Thu, 22 Sep 2022 12:39:12 -0400 Subject: [PATCH] fix(types): add HydratedDocumentFromSchema to make it easier to pull inferred hydrated doc type Fix #12319 --- .eslintrc.json | 1 + test/types/models.test.ts | 26 ++++++++++++++++++++++++++ types/index.d.ts | 6 ++++++ 3 files changed, 33 insertions(+) diff --git a/.eslintrc.json b/.eslintrc.json index 589be0e1799..c9747d96875 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -25,6 +25,7 @@ "rules": { "@typescript-eslint/triple-slash-reference": "off", "@typescript-eslint/no-non-null-assertion": "off", + "@typescript-eslint/no-empty-function": "off", "spaced-comment": [ "error", "always", diff --git a/test/types/models.test.ts b/test/types/models.test.ts index a47a84a8d16..254ecc483ee 100644 --- a/test/types/models.test.ts +++ b/test/types/models.test.ts @@ -9,6 +9,7 @@ import { UpdateQuery, CallbackError, HydratedDocument, + HydratedDocumentFromSchema, LeanDocument, Query, UpdateWriteOpResult @@ -494,3 +495,28 @@ async function gh12347() { const replaceOneResult = await User.replaceOne({}, {}); expectType(replaceOneResult); } + +async function gh12319() { + const projectSchema = new Schema( + { + name: { + type: String, + required: true + } + }, + { + methods: { + async doSomething() { + } + } + } + ); + + const ProjectModel = model('Project', projectSchema); + + type ProjectModelHydratedDoc = HydratedDocumentFromSchema< + typeof projectSchema + >; + + expectType(await ProjectModel.findOne().orFail()); +} diff --git a/types/index.d.ts b/types/index.d.ts index 60cac795520..e6ec1f23f69 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -118,6 +118,12 @@ declare module 'mongoose' { export type HydratedDocument = DocType extends Document ? Require_id : (Document & Require_id & TVirtuals & TMethodsAndOverrides); + export type HydratedDocumentFromSchema = HydratedDocument< + InferSchemaType, + ObtainSchemaGeneric, + ObtainSchemaGeneric + >; + export interface TagSet { [k: string]: string; }