有没有一种方法可以将像下面这样的有效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` 你尝试过嵌套模式吗?你只能使用引用或数组进行嵌套。
- veichnew Schema
。 - Edgar{type: 'SOME_MONGOOSE_TYPE'}
。因此,您的 JSON 中的每个键都应该是一个对象,在该对象中存在类型属性。如果您想要深度嵌套对象,请将它们定义为其他模式,并且主对象应为{type:'NAME_OF_OTHER_SCHEMA'}
。 - Edgar