【问题标题】:How to convert JSON schema to mongoose schema如何将 JSON 模式转换为猫鼬模式
【发布时间】:2017-07-08 16:14:00
【问题描述】:

有没有一种方法可以采用如下所示的有效 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 模式的示例,还有很多如何从这样的对象创建猫鼬模式的示例:
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.

但是我在网上找不到从一种类型到另一种类型的转移。
以前有人遇到过这个问题吗?

编辑:

这个问题在概念上是不正确的。
基本上,您所做的是针对数据 将其保存到 DB 之前验证 JSON 模式。您可以使用来自 npm 或其他的 jsonschema 来执行此操作。
因此数据验证步骤与保存到数据库步骤没有直接联系。
我认为您可以将 JSON 模式应用于 MongoDB 模式,但事实并非如此。 (尤其是当你有深层嵌套的对象时——那就一团糟)

【问题讨论】:

  • 看不到从一种类型到另一种类型的转移是什么意思?
  • 我的意思是我无法通过谷歌搜索在互联网上找到它。
  • 在您的情况下const newSchema = new mongoose.Schema(YOUR_JSON_SCHEMA); 有什么问题?
  • 我得到一个错误:``` .../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 你试过嵌套 Schemas 吗?你只能嵌套使用 refs 或数组。```
  • 我认为您也应该将所有嵌套对象都转换为new Schema

标签: node.js mongoose schema jsonschema


【解决方案1】:

我一直在研究这个。由于您在问题上放置了node 标签,因此我找到了这些npm repos:

到目前为止,两者都在工作。

他们都几岁了。前者(TypeScript)有更新的提交。我可能最终会更喜欢后者。

【讨论】:

    【解决方案2】:

    【讨论】:

    • 已经看过了,这绝对不是我想要的。这会将 JSON 数据转换为 JSON 模式。我已经有 JSON 模式并且需要猫鼬模式。感谢您的努力,但不幸的是,我将不得不对这个答案投反对票。此外,您建议的这个链接是我在搜索您遇到问题的地方时发现的示例之一,并且有人提供了解决方案是 JSON 模式的解决方案(好像这是故事的结尾)。我的意思是 - 我该如何处理 JSON 架构?
    • 仅链接自动标记为低质量的答案,应避免这样做。
    猜你喜欢
    • 2017-10-27
    • 2020-01-17
    • 2016-08-05
    • 2018-04-08
    • 1970-01-01
    • 2012-02-02
    • 2014-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多