如何将JSON模式转换为Mongoose模式

7
有没有一种方法可以将像下面这样的有效JSON模式转换为mongoose模式?
{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "description": "some desc",
  "title": "Product",
  "type": "object",
  "properties": {
    "endpoints": {
      "type": "array",
      "items": {
        "type": "string"
      }
    },
    "poi": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "location_name": {
            "type": "string"
          },
          "distance": {
            "type": "string"
          }
        }
      }
    }
  }
}

这对我来说似乎很基础和简单,但我在网络上找不到任何信息。
有很多关于如何获取JSON模式的示例,也有很多如何从像这样的对象创建mongoose模式的示例:
const newSchema = new mongoose.Schema({ name: String });

如果我尝试直接放置JSON模式,则会出现错误。

node_modules/mongoose/lib/schema.js:674
    throw new TypeError('Undefined type `' + name + '` at `' + path +
    ^

TypeError: Undefined type `Http://json-schema.org/draft-04/schema#` at `$schema`
  Did you try nesting Schemas? You can only nest using refs or arrays.

但我在网上找不到从一种类型转换为另一种类型的方法。
有人之前遇到过这个问题吗?

编辑:

这个问题在概念上是不正确的。
基本上,在将数据保存到数据库之前,您需要使用npm或其他工具中的jsonschema对JSON模式进行验证。
因此,数据验证步骤与保存到数据库步骤没有直接关联。
我曾以为可以将JSON模式应用于MongoDB模式,但事实并非如此(特别是当您有深度嵌套对象时,那就很混乱了)。


在你的情况下,const newSchema = new mongoose.Schema(YOUR_JSON_SCHEMA); 有什么问题吗? - Edgar
我遇到了一个错误:.../node_modules/mongoose/lib/schema.js:674 throw new TypeError('Undefined type `' + name + '` at `' + path + ^ TypeError: Undefined type `Http://json-schema.org/draft-04/schema#` at `$schema` 你尝试过嵌套模式吗?你只能使用引用或数组进行嵌套。 - veich
我认为你应该将所有嵌套对象也转换为 new Schema - Edgar
好主意,但是没有起作用 :) 我移除了嵌套对象并尝试了一下,但仍然出现相同的错误。 - veich
对于每个键,您应该提供 {type: 'SOME_MONGOOSE_TYPE'}。因此,您的 JSON 中的每个键都应该是一个对象,在该对象中存在类型属性。如果您想要深度嵌套对象,请将它们定义为其他模式,并且主对象应为 {type:'NAME_OF_OTHER_SCHEMA'} - Edgar
显示剩余3条评论
1个回答

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接