You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
@@ -720,6 +722,122 @@ The following inputs will result will all result in a [CastError](validation.htm
720
722
* a decimal that must be rounded to be an integer
721
723
* an input that represents a value outside the bounds of an 32-bit integer
722
724
725
+
### Union {#union}
726
+
727
+
The `Union` SchemaType allows a path to accept multiple types. Mongoose will attempt to cast the value to one of the specified types.
728
+
729
+
```javascript
730
+
constschema=newSchema({
731
+
value: {
732
+
type:Schema.Types.Union,
733
+
of: [String, Number]
734
+
}
735
+
});
736
+
737
+
constModel=mongoose.model('Model', schema);
738
+
739
+
// Both work - Mongoose accepts either type
740
+
constdoc1=newModel({ value:'hello' });
741
+
constdoc2=newModel({ value:42 });
742
+
```
743
+
744
+
#### Casting Behavior
745
+
746
+
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
+
748
+
```javascript
749
+
constschema=newSchema({
750
+
flexibleField: {
751
+
type:Schema.Types.Union,
752
+
of: [Number, Date]
753
+
}
754
+
});
755
+
756
+
constModel=mongoose.model('Model', schema);
757
+
758
+
// Number type
759
+
constdoc1=newModel({ flexibleField:42 });
760
+
doc1.flexibleField; // 42 (number)
761
+
762
+
// String '42' gets cast to Number (first type that succeeds)
0 commit comments