Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: add brief note on TypeScript generic usage for embedded discriminator path() calls #13728

Merged
merged 1 commit into from Aug 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 24 additions & 0 deletions docs/discriminators.md
Expand Up @@ -53,3 +53,27 @@ To update a document's discriminator key, use `findOneAndUpdate()` or `updateOne
```acquit
[require:use overwriteDiscriminatorKey to change discriminator key]
```

## Embedded discriminators in arrays

You can also define discriminators on embedded document arrays.
Embedded discriminators are different because the different discriminator types are stored in the same document array (within a document) rather than the same collection.
In other words, embedded discriminators let you store subdocuments matching different schemas in the same array.

As a general best practice, make sure you declare any hooks on your schemas **before** you use them.
You should **not** call `pre()` or `post()` after calling `discriminator()`.

```acquit
[require:Embedded discriminators in arrays]
```

## Single nested discriminators

You can also define discriminators on single nested subdocuments, similar to how you can define discriminators on arrays of subdocuments.

As a general best practice, make sure you declare any hooks on your schemas **before** you use them.
You should **not** call `pre()` or `post()` after calling `discriminator()`.

```acquit
[require:Single nested discriminators]
```
2 changes: 2 additions & 0 deletions test/docs/discriminators.test.js
Expand Up @@ -273,6 +273,7 @@ describe('discriminator docs', function() {
const batchSchema = new Schema({ events: [eventSchema] });

// `batchSchema.path('events')` gets the mongoose `DocumentArray`
// For TypeScript, use `schema.path<Schema.Types.DocumentArray>('events')`
const docArray = batchSchema.path('events');

// The `events` array can contain 2 different types of events, a
Expand Down Expand Up @@ -391,6 +392,7 @@ describe('discriminator docs', function() {
const shapeSchema = Schema({ name: String }, { discriminatorKey: 'kind' });
const schema = Schema({ shape: shapeSchema });

// For TypeScript, use `schema.path<Schema.Types.Subdocument>('shape').discriminator(...)`
schema.path('shape').discriminator('Circle', Schema({ radius: String }));
schema.path('shape').discriminator('Square', Schema({ side: Number }));

Expand Down