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,117 @@ 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
+
```javascript
729
+
constschema=newSchema({
730
+
value: {
731
+
type:Schema.Types.Union,
732
+
of: [String, Number]
733
+
}
734
+
});
735
+
736
+
constModel=mongoose.model('Model', schema);
737
+
738
+
// Both work - Mongoose accepts either type
739
+
constdoc1=newModel({ value:'hello' });
740
+
constdoc2=newModel({ value:42 });
741
+
```
742
+
743
+
#### Casting Behavior
744
+
745
+
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.
746
+
```javascript
747
+
constschema=newSchema({
748
+
flexibleField: {
749
+
type:Schema.Types.Union,
750
+
of: [Number, Date]
751
+
}
752
+
});
753
+
754
+
constModel=mongoose.model('Model', schema);
755
+
756
+
// Number type
757
+
constdoc1=newModel({ flexibleField:42 });
758
+
doc1.flexibleField; // 42 (number)
759
+
760
+
// String '42' gets cast to Number (first type that succeeds)
0 commit comments