Skip to content

Commit 3660041

Browse files
committed
docs(typescript): add section on InferRawDocType to TypeScript docs
1 parent 09bdf11 commit 3660041

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

docs/typescript/schemas.md

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ Mongoose can automatically infer the document type from your schema definition a
99
We recommend relying on automatic type inference when defining schemas and models.
1010

1111
```typescript
12-
import { Schema } from 'mongoose';
12+
import { Schema, model } from 'mongoose';
1313
// Schema
1414
const schema = new Schema({
1515
name: { type: String, required: true },
@@ -32,6 +32,31 @@ There are a few caveats for using automatic type inference:
3232
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.
3333
3. Mongoose adds `createdAt` and `updatedAt` to your schema if you specify the `timestamps` option in your schema, *except* if you also specify `methods`, `virtuals`, or `statics`. There is a [known issue](https://github.com/Automattic/mongoose/issues/12807) with type inference with timestamps and methods/virtuals/statics options. If you use methods, virtuals, and statics, you're responsible for adding `createdAt` and `updatedAt` to your schema definition.
3434

35+
If you need to explicitly get the raw document type (the value returned from `doc.toObject()`, `await Model.findOne().lean()`, etc.) from your schema definition, you can use Mongoose's `inferRawDocType` helper as follows:
36+
37+
```ts
38+
import { Schema, InferRawDocType, model } from 'mongoose';
39+
40+
const schemaDefinition = {
41+
name: { type: String, required: true },
42+
email: { type: String, required: true },
43+
avatar: String
44+
} as const;
45+
const schema = new Schema(schemaDefinition);
46+
47+
const UserModel = model('User', schema);
48+
const doc = new UserModel({ name: 'test', email: 'test' });
49+
50+
type RawUserDocument = InferRawDocType<typeof schemaDefinition>;
51+
52+
useRawDoc(doc.toObject());
53+
54+
function useRawDoc(doc: RawUserDocument) {
55+
// ...
56+
}
57+
58+
```
59+
3560
If automatic type inference doesn't work for you, you can always fall back to document interface definitions.
3661

3762
## Separate document interface definition

0 commit comments

Comments
 (0)