Skip to content

Commit 2f7d2c1

Browse files
authored
Enhance documentation for Union SchemaType
Added examples and explanations for Union SchemaType.
1 parent 6493a96 commit 2f7d2c1

File tree

1 file changed

+5
-0
lines changed

1 file changed

+5
-0
lines changed

docs/schematypes.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -725,6 +725,7 @@ The following inputs will result will all result in a [CastError](validation.htm
725725
### Union {#union}
726726

727727
The `Union` SchemaType allows a path to accept multiple types. Mongoose will attempt to cast the value to one of the specified types.
728+
728729
```javascript
729730
const schema = new Schema({
730731
value: {
@@ -743,6 +744,7 @@ const doc2 = new Model({ value: 42 });
743744
#### Casting Behavior
744745

745746
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.
747+
746748
```javascript
747749
const schema = new Schema({
748750
flexibleField: {
@@ -773,6 +775,7 @@ doc4.flexibleField; // Date object
773775
#### Error Handling
774776

775777
If Mongoose cannot cast the value to any of the specified types, it throws the error from the last type in the union.
778+
776779
```javascript
777780
const schema = new Schema({
778781
value: {
@@ -790,6 +793,7 @@ const doc = new Model({ value: 'not a number or boolean' });
790793
#### Union with Options
791794

792795
You can specify options for individual types in the union, such as `trim` for strings.
796+
793797
```javascript
794798
const schema = new Schema({
795799
value: {
@@ -810,6 +814,7 @@ doc.value; // 'hello' (trimmed)
810814
#### Queries and Updates
811815

812816
Union types work with queries and updates. Mongoose casts query filters and update operations according to the union types.
817+
813818
```javascript
814819
const schema = new Schema({
815820
value: {

0 commit comments

Comments
 (0)