简体   繁体   中英

How to declare an array of different types in a Mongoose schema?

I am trying to create a Mongoose schema which contains a field that should be an array that contains different types/objects.

For example:

myArrayField: [
 { type: 'type1', type1Property: 'blabla', type1Property2: 'blabla'},
 { type: 'type2', type2Property2: 'blablo' }
]

I have taken a look at discriminators without any success and I have found mongoose.Schema.Types.Mixed. However, Mixed seems to be very open in terms that Mongo will not check anything about it. I would like to know if I can specify the different types the array can have, something like:

myArrayField: [ SchemaType1, SchemaType2]

So items can follow SchemaType1 OR SchemaType2.

Thank you in advance and regards

Only one type can be assigned to a field. May be you should create one schema with two fields that has different types and required attributes are set to false which is default.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM