-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
docs: add documentation for Union Schema Type #15721
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
Merged
vkarpov15
merged 3 commits into
Automattic:master
from
TechGenie-awake:docs-union-schema-type
Nov 9, 2025
+118
−0
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -48,6 +48,7 @@ Check out [Mongoose's plugins search](http://plugins.mongoosejs.io) to find plug | |
| * [Buffer](#buffers) | ||
| * [Boolean](#booleans) | ||
| * [Mixed](#mixed) | ||
| * [Union](#union) | ||
| * [ObjectId](#objectids) | ||
| * [Array](#arrays) | ||
| * [Decimal128](api/mongoose.html#mongoose_Mongoose-Decimal128) | ||
|
|
@@ -68,6 +69,7 @@ const schema = new Schema({ | |
| updated: { type: Date, default: Date.now }, | ||
| age: { type: Number, min: 18, max: 65 }, | ||
| mixed: Schema.Types.Mixed, | ||
| union: { type: Schema.Types.Union, of: [String, Number] }, | ||
| _someId: Schema.Types.ObjectId, | ||
| decimal: Schema.Types.Decimal128, | ||
| double: Schema.Types.Double, | ||
|
|
@@ -720,6 +722,122 @@ The following inputs will result will all result in a [CastError](validation.htm | |
| * a decimal that must be rounded to be an integer | ||
| * an input that represents a value outside the bounds of an 32-bit integer | ||
|
|
||
| ### Union {#union} | ||
|
|
||
| The `Union` SchemaType allows a path to accept multiple types. Mongoose will attempt to cast the value to one of the specified types. | ||
|
|
||
| ```javascript | ||
| const schema = new Schema({ | ||
| value: { | ||
| type: Schema.Types.Union, | ||
| of: [String, Number] | ||
| } | ||
| }); | ||
|
|
||
| const Model = mongoose.model('Model', schema); | ||
|
|
||
| // Both work - Mongoose accepts either type | ||
| const doc1 = new Model({ value: 'hello' }); | ||
| const doc2 = new Model({ value: 42 }); | ||
| ``` | ||
|
|
||
| #### Casting Behavior | ||
|
|
||
| When you set a value on a Union path, Mongoose tries to cast it to each type in the `of` array in order. If the value matches one of the types exactly (using `===`), Mongoose uses that value. Otherwise, Mongoose uses the first type that successfully casts the value. | ||
|
|
||
| ```javascript | ||
| const schema = new Schema({ | ||
| flexibleField: { | ||
| type: Schema.Types.Union, | ||
| of: [Number, Date] | ||
| } | ||
| }); | ||
|
|
||
| const Model = mongoose.model('Model', schema); | ||
|
|
||
| // Number type | ||
| const doc1 = new Model({ flexibleField: 42 }); | ||
| doc1.flexibleField; // 42 (number) | ||
|
|
||
| // String '42' gets cast to Number (first type that succeeds) | ||
| const doc2 = new Model({ flexibleField: '42' }); | ||
| doc2.flexibleField; // 42 (number) | ||
|
|
||
| // Date type | ||
| const doc3 = new Model({ flexibleField: new Date('2025-06-01') }); | ||
| doc3.flexibleField; // Date object | ||
|
|
||
| // String date gets cast to Date | ||
| const doc4 = new Model({ flexibleField: '2025-06-01' }); | ||
| doc4.flexibleField; // Date object | ||
| ``` | ||
|
|
||
| #### Error Handling | ||
|
|
||
| If Mongoose cannot cast the value to any of the specified types, it throws the error from the last type in the union. | ||
|
|
||
| ```javascript | ||
| const schema = new Schema({ | ||
| value: { | ||
| type: Schema.Types.Union, | ||
| of: [Number, Boolean] | ||
| } | ||
| }); | ||
|
|
||
| const Model = mongoose.model('Model', schema); | ||
|
|
||
| const doc = new Model({ value: 'not a number or boolean' }); | ||
| // Throws: Cast to Boolean failed for value "not a number or boolean" | ||
| ``` | ||
|
|
||
| #### Union with Options | ||
|
|
||
| You can specify options for individual types in the union, such as `trim` for strings. | ||
|
|
||
| ```javascript | ||
| const schema = new Schema({ | ||
| value: { | ||
| type: Schema.Types.Union, | ||
| of: [ | ||
| Number, | ||
| { type: String, trim: true } | ||
| ] | ||
| } | ||
| }); | ||
|
|
||
| const Model = mongoose.model('Model', schema); | ||
|
|
||
| const doc = new Model({ value: ' hello ' }); | ||
| doc.value; // 'hello' (trimmed) | ||
| ``` | ||
|
|
||
| #### Queries and Updates | ||
|
|
||
| Union types work with queries and updates. Mongoose casts query filters and update operations according to the union types. | ||
|
|
||
| ```javascript | ||
| const schema = new Schema({ | ||
| value: { | ||
| type: Schema.Types.Union, | ||
| of: [Number, Date] | ||
| } | ||
| }); | ||
|
|
||
| const Model = mongoose.model('Model', schema); | ||
|
|
||
| await Model.create({ value: 42 }); | ||
|
|
||
| // Query with string - gets cast to number | ||
| const doc = await Model.findOne({ value: '42' }); | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This one is incorrect because of the "exact match" rule - since String is one of the valid types, Mongoose will leave '42' as a string. |
||
| doc.value; // 42 | ||
|
|
||
vkarpov15 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| // Update | ||
| await Model.findOneAndUpdate( | ||
| { value: 42 }, | ||
| { value: new Date('2025-06-01') } | ||
| ); | ||
| ``` | ||
|
|
||
| ## Getters {#getters} | ||
|
|
||
| Getters are like virtuals for paths defined in your schema. For example, | ||
|
|
||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.