可以仅将JsonSchema与Mongoose一起使用吗?

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的方法,有什么建议吗?

mrt*_*taz 2

也许这个,看起来它从条目导入你的 ajv 模式并将其放置在 mongoose 模式中。https://www.npmjs.com/package/mongoose-ajv-plugin