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