Mongoose - 验证不同子文档类型的数组
Posted
技术标签:
【中文标题】Mongoose - 验证不同子文档类型的数组【英文标题】:Mongoose - Validate array of different subdocuments types 【发布时间】:2018-04-15 17:08:21 【问题描述】:我有一个包含不同子文档类型数组的架构。 下面的架构只是一个例子:
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 中传递的“类型”来验证“vehiclesSelected”数组。有人可以告诉我如何验证 基于特定字段(在本例中为“类型”)的子文档数组?
任何帮助将不胜感激。
【问题讨论】:
我也遇到了同样的问题,也期待有人帮助我。干杯 如果您设法找到解决方案,请告诉我。 vehiclesSelected: [BikeSchema, TruckSchema] --> 你能做到吗?最新版本的 Mongoose 是否支持? 【参考方案1】:你可以使用 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)。
【讨论】:
以上是关于Mongoose - 验证不同子文档类型的数组的主要内容,如果未能解决你的问题,请参考以下文章
在 Mongoose/MongoDB 的文档中过滤数组、子文档、数组、文档