我有以下Mongoose模型:
RequestSchema = mongoose.Schema(
merchant:
type: String
required: true
products: [ 'Product' ]
)
Request = mongoose.model('Request', RequestSchema)
ProductSchema = mongoose.Schema(
_type: String
product_id:
type: String
required: true
quantity:
type: String
required: true
)
Product = mongoose.model('Product', ProductSchema)
但是,当我传入以下请求(缺少数量)时,它会被验证并保存到数据库中:
{"merchant": "ABC", "products":[{"product_id":"12345"}]}
但是,当我尝试省略商家时,它会尝试保存模式验证错误:
{"products":[{"product_id":"12345", "quantity": "1"}]}
如何使它们都返回验证错误?
答案 0 :(得分:1)
如果要使用子文档并对其进行验证,则需要引用架构对象:
ProductSchema = mongoose.Schema(...)
RequestSchema = mongoose.Schema(
merchant:
type: String
required: true
products: [ ProductSchema ]
)
这将在第一个文档中给出验证错误:
ValidationError: Path `quantity` is required.