我有一个包含不同子文档类型数组的模式。 下面的架构只是一个例子:
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"}
]
}
现在我需要根据JSON中传递的'type'验证“vehiclesSelected”数组。有人能告诉我如何验证 基于特定字段的子文档数组(在本例中为'type')?
非常感谢任何帮助。
答案 0 :(得分:2)
您可以使用Mongoose的discriminator()函数。
在您的情况下,您可以做的是:
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))
这样,根据车辆类型,您的架构将使用适当的子类型进行验证,两者都继承父模式(在本例中为typeVehicleSchema),基于传入的“类型”。