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

Using only JsonSchema with Mongoose possible?

我有一个 api 使用 express,mongodb 并且我使用 AJV 验证来验证传入的请求。

//JSONSchema
var recordJsonSchema = {
     type: "object",
     properties: {
         name: { type: "string" },
         idNumber: { type: "number" },
         content: { type: "string" }
     },
     required: ['name','idNumber']
}

我会像这样使用这个 JSON 模式来验证传入的请求。

app.post('/record', (req,res) => {
   let errors = ajv.inspect(req.body, recordJsonSchema)
   return errors ? res.send(errors) : res.send(this.handler(req));
})

这很好用而且速度很快。我也喜欢 JsonSchema,因为它遵循 OpenAPI 标准。

不幸的是,为了通过 mongoose read/write 到 mongo,我还需要创建一个 MongoSchema for Record。它们非常相似,但在处理必填字段等方面有些不同。

var recordSchema = new Schema({
   name: { type: "string", required: true },
   idNumber: { type: "number", required: true },
   content: { type: "string" }
})

所以对于我的 Record 模型,我现在有两个模式。一个用于 JSON 模式,一个用于处理 Mongo read/writes。

我正在寻找一种方法来削减 MongoSchema,有什么建议吗?

也许是这样,它似乎从条目中导入了您的 ajv 模式并将其放置在 mongoose 模式中。 https://www.npmjs.com/package/mongoose-ajv-plugin

我也遇到过同样的问题。我认为在新的 mongo 4.4 中我们可以将 ajv 模式直接加载到 mongodb https://docs.mongodb.com/manual/reference/operator/query/jsonSchema/