【发布时间】: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 typeHttp://json-schema.org/draft-04/schema#` at$schema你试过嵌套 Schemas 吗?你只能嵌套使用 refs 或数组。``` -
我认为您也应该将所有嵌套对象都转换为
new Schema。
标签: node.js mongoose schema jsonschema