node.js - 如何将 JSON 模式转换为 Mongoose 模式

标签 node.js mongoose schema jsonschema

有没有一种方法可以采用如下所示的有效 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.

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

编辑:

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

最佳答案

我一直在研究这个。因为你在你的问题上放置了一个 node 标签,我找到了这些 npm repo :

目前两者都在工作。

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

关于node.js - 如何将 JSON 模式转换为 Mongoose 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42326673/

相关文章:

node.js - 请求超时时,nodejs http.request关闭过程

node.js - express.js 未在 NodeUnit 测试中保存 session 数据

node.js - 如何在 MEAN 堆栈应用程序中从后端到前端进行通信?

node.js - Mongoose 在更新时覆盖字段

json - 确保对象字段的值存在于 Json Schema 的另一个字段中

javascript - Mocha 在导入的代码中找不到模块

node.js - Jade 模板引擎,如何使用layout.jade?

node.js - 连接到 mongoose 的语法

xml - XML 验证器如何知道在哪里可以找到在 xml 文档中声明的模式实例以便解析和使用 xsd?

schema - 如何使用 dateModified 微数据