Pro*_*imo 5 validation jsonschema mongodb node.js express
我有一个使用express,mongodb的api,并且使用AJV验证来验证传入的请求。
//JSONSchema
var recordJsonSchema = {
type: "object",
properties: {
name: { type: "string" },
idNumber: { type: "number" },
content: { type: "string" }
},
required: ['name','idNumber']
}
Run Code Online (Sandbox Code Playgroud)
我将使用这种JSON模式来验证传入的请求。
app.post('/record', (req,res) => {
let errors = ajv.inspect(req.body, recordJsonSchema)
return errors ? res.send(errors) : res.send(this.handler(req));
})
Run Code Online (Sandbox Code Playgroud)
这工作正常并且非常快。我也喜欢JsonSchema,因为它遵循OpenAPI标准。
不幸的是,为了通过mongoose读/写mongo,我还需要创建一个MongoSchema for Record。它们非常相似,但在处理必填字段等方面却有些不同。
var recordSchema = new Schema({
name: { type: "string", required: true },
idNumber: { type: "number", required: true },
content: { type: "string" }
})
Run Code Online (Sandbox Code Playgroud)
因此,对于我的记录模型,我现在有两个模式。一种用于JSONschema,另一种用于处理Mongo读/写。
我正在寻找一种削减MongoSchema的方法,有什么建议吗?
| 归档时间: |
|
| 查看次数: |
767 次 |
| 最近记录: |