gpt4 book ai didi

node.js - Express-Validator 检查子文档数组

转载 作者:搜寻专家 更新时间:2023-11-01 00:05:29 26 4
gpt4 key购买 nike

这是我的架构:

const InvoiceSchema = new Schema({
name: { type: String, required: true },
description: { type: String },

items: [{
name: { type: String, required: true },
rate: { type: Number, required: true },
quantity: { type: Number, required:true, default: 1 },
amount: { type: Number }
}]});

我想知道如何使用 Express-validator 来检查 items 元素?

最佳答案

之前遇到过同样的问题,这非常痛苦,尤其是当它是一个深层数组或要验证的对象数组时。我最终创建了自己的验证器(wallter)来处理这个问题。而且此工具还可以直接从您的 Mongoose 模型生成验证模式。

因此您上面的模式将生成一个验证模式:

{
"name": {
"required": {
"msg": "Value for field 'name' is required"
}
},
"description": {
"optional": true
},
"items.*.name": {
"required": {
"msg": "Value for field 'items.*.name' is required"
}
},
"items.*.rate": {
"required": {
"msg": "Value for field 'items.*.rate' is required"
},
"isDecimal": {
"msg": "Expecting 'decimal' value for field 'items.*.rate'"
}
},
"items.*.quantity": {
"required": {
"msg": "Value for field 'items.*.quantity' is required"
},
"isDecimal": {
"msg": "Expecting 'decimal' value for field 'items.*.quantity'"
}
},
"items.*.amount": {
"optional": true,
"isDecimal": {
"msg": "Expecting 'decimal' value for field 'items.*.amount'"
}
}
}

可以将此验证模式提供给验证器

const halter = require('wallter').halter
const Builder = require('wallter').builder // validation schema builder

const builder = new Builder({
model: mongoose.model('YourModelName')
})

server.use(halter())

server.post('/test', function (req, res, next) {
let validationSchema = builder.build() // see above generated validation schema output

req.halt(validationSchema).then(result => {
if (result.length) {
res.send(400, result)
} else {
res.send(200)
}

return next()
})
})

关于node.js - Express-Validator 检查子文档数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43667006/

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