From bb874d9f236b11bff37e7be3cad1f811b44f254e Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Thu, 22 Dec 2022 13:56:10 -0500 Subject: [PATCH] docs(typescript): make note about recommending `strict` mode when using auto typed schemas Re: #12420 --- docs/typescript/schemas.md | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/docs/typescript/schemas.md b/docs/typescript/schemas.md index 656c058d5c6..80a86ed126d 100644 --- a/docs/typescript/schemas.md +++ b/docs/typescript/schemas.md @@ -1,11 +1,9 @@ # Schemas in TypeScript Mongoose [schemas](../guide.html) are how you tell Mongoose what your documents look like. -Mongoose schemas are separate from TypeScript interfaces, so you need to define both a _document interface_ and a _schema_ until V6.3.1. -Mongoose supports auto typed schemas so you don't need to define additional typescript interface anymore but you are still able to do so. -Mongoose provides a `InferSchemaType`, which infers the type of the auto typed schema document when needed. +Mongoose schemas are separate from TypeScript interfaces, so you need to either define both a _document interface_ and a _schema_; or rely on Mongoose to automatically infer the type from the schema definition. -`Until mongoose V6.3.1:` +### Separate document interface definition ```typescript import { Schema } from 'mongoose'; @@ -25,7 +23,12 @@ const schema = new Schema({ }); ``` -`another approach:` +By default, Mongoose does **not** check if your document interface lines up with your schema. +For example, the above code won't throw an error if `email` is optional in the document interface, but `required` in `schema`. + +### Automatic type inference + +Mongoose can also automatically infer the document type from your schema definition as follows. ```typescript import { Schema, InferSchemaType } from 'mongoose'; @@ -53,11 +56,16 @@ type User = InferSchemaType; // avatar?: string; // } - +// `UserModel` will have `name: string`, etc. +const UserModel = mongoose.model('User', schema); ``` -By default, Mongoose does **not** check if your document interface lines up with your schema. -For example, the above code won't throw an error if `email` is optional in the document interface, but `required` in `schema`. +There are a few caveats for using automatic type inference: + +1. You need to set `strict: true` in your `tsconfig.json` or `--strict` if running `tsc`. There are [known issues](https://github.com/Automattic/mongoose/issues/12420) with automatic type inference with strict mode disabled. +2. You need to define your schema in the `new Schema()` call. Don't assign your schema definition to a temporary variable. Doing something like `const schemaDefinition = { name: String }; const schema = new Schema(schemaDefinition);` will not work. + +If automatic type inference doesn't work for you, you can always fall back to document interface definitions. ## Generic parameters