gpt4 book ai didi

node.js - Mongoose 嵌套架构验证不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 01:08:14 25 4
gpt4 key购买 nike

我有以下 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"}]} 

如何才能使它们都返回验证错误?

最佳答案

当您想要使用子文档并验证它们时,您需要引用架构对象:

ProductSchema = mongoose.Schema(...)

RequestSchema = mongoose.Schema(
merchant:
type: String
required: true
products: [ ProductSchema ]
)

这将在第一个文档上产生验证错误:

ValidationError: Path `quantity` is required.

关于node.js - Mongoose 嵌套架构验证不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20829600/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com