Sreerama Akunuru
Sreerama Akunuru

Reputation: 11

Mongoose - Validate array of different subdocuments types

I have a schema which has an array of different sub document types. Below schema is just an example:

VehicleSchema:

let BikeSchema = new Schema({
  title       : { type: String, required: [true, 'title is required'] },
  type        : { type: String, required: true, default: "bike" },
  tyres       : { type: Number, required: true, min: 2}
});

let TruckSchema = new Schema({
  title       : { type: String, required: [true, 'title is required'] },
  type        : { type: String, required: true, default: "truck" },
  tyres       : { type: Number, required: true, min: 4},
  doors       : { type: Number, required: true}
});

let VehicleSchema = new Schema({
  name: {type:String, required: [true, 'name is required']},
  vehiclesSelected: [BikeSchema, TruckSchema],
});

Below is the json that I need to validate:
vehicle = {
  "name": 'abc',
  "vehiclesSelected": [
    {"type": "truck", doors: 2},
    {"type": "bike", tyres: 3},
    {"type": "bike"}
  ]
}

Now I need to validate the "vehiclesSelected" array based on the 'type' passed in the JSON. Can someone tell me how can I validate an array of subdocuments based on a particular field (in this case 'type')?

Any help would be much appreciated.

Upvotes: 1

Views: 832

Answers (1)

Ryan W Kan
Ryan W Kan

Reputation: 380

You can make use of Mongoose's discriminator() function.

In your case, what you can do is:

let BikeSchema = new Schema({
  title       : { type: String, required: [true, 'title is required'] },
  tyres       : { type: Number, required: true, min: 2}
});

let TruckSchema = new Schema({
  title       : { type: String, required: [true, 'title is required'] },
  tyres       : { type: Number, required: true, min: 4},
  doors       : { type: Number, required: true}
});

let typeVehicleSchema = new Schema({},
discriminatorKey: 'type', _id: false})

let VehicleSchema = new Schema({
  name: {type:String, required: [true, 'name is required']},
  vehiclesSelected: [typeVehicleSChema],
});

VehicleSchema.path('vehiclesSelected').discriminator('truck', new Schema(TruckSchema))
VehicleSchema.path('vehiclesSelected').discriminator('bike', new Schema(BikeSchema))

That way, depending on vehicle type, your schema will validate with the appropriate subType, both inheriting the parent schema (in this case, the typeVehicleSchema), based on the 'type' passed in.

Upvotes: 2

Related Questions