【发布时间】:2018-06-15 09:50:37
【问题描述】:
我有一个 JSON 文件,我想在 MongoDB 上使用 JSON Schema 验证该文件。 如何将 JSON 架构导入 MongoDB,然后验证 JSON 文件。 JSON 文件已经在一个集合中,所以我想在不导入新 JSON 文件的情况下进行验证。
JSON:
{
"Book": {
"Year:2016-2017": {
"Crs": [{
"Cr": {
"_id": {
"$oid": "5a439ff4fc0900f06fb470a4"
},
"Number": 35,
"Pag": 8,
"Desc": "Embl",
"Ad": "S",
"Type": "Embl"
}
}]
}
}
}
JSON 架构:
{
"type": "object",
"$schema": "http://json-schema.org/draft-03/schema",
"id": "http://jsonschema.net",
"required": false,
"properties": {"Book": {
"type": "object",
"id": "http://jsonschema.net/Book",
"required": false,
"properties": {"Year:2016-2017": {
"type": "object",
"id": "http://jsonschema.net/Book/Year:2016-2017",
"required": false,
"properties": {"Crs": {
"type": "array",
"id": "http://jsonschema.net/Book/Year:2016-2017/Crs",
"required": false,
"items": {
"type": "object",
"id": "http://jsonschema.net/Book/Year:2016-2017/Crs/0",
"required": false,
"properties": {"Cr": {
"type": "object",
"id": "http://jsonschema.net/Book/Year:2016-2017/Crs/0/Cr",
"required": false,
"properties": {
"Ad": {
"type": "string",
"id": "http://jsonschema.net/Book/Year:2016-2017/Crs/0/Cr/Ad",
"required": false
},
"Desc": {
"type": "string",
"id": "http://jsonschema.net/Book/Year:2016-2017/Crs/0/Cr/Desc",
"required": false
},
"Number": {
"type": "number",
"id": "http://jsonschema.net/Book/Year:2016-2017/Crs/0/Cr/Number",
"required": false
},
"Pag": {
"type": "number",
"id": "http://jsonschema.net/Book/Year:2016-2017/Crs/0/Cr/Pag",
"required": false
},
"Type": {
"type": "string",
"id": "http://jsonschema.net/Book/Year:2016-2017/Crs/0/Cr/Type",
"required": false
},
"_id": {
"type": "object",
"id": "http://jsonschema.net/Book/Year:2016-2017/Crs/0/Cr/_id",
"required": false,
"properties": {"$oid": {
"type": "string",
"id": "http://jsonschema.net/Book/Year:2016-2017/Crs/0/Cr/_id/$oid",
"required": false
}}
}
}
}}
}
}}
}}
}}}
我想使用带有 mongodb 的模式来验证 JSON。
【问题讨论】:
-
在创建集合时导入 json 模式,它会在您插入文档时验证它们。类似
db.createCollection(colname, { validator: {$jsonschema: schema }}); -
@Veeram 我已经在集合中有 json 文件(不是架构)。无论如何,在不创建新集合的情况下验证该文件?像 XML 架构
-
所以您想在使用您拥有的 json 模式进行查询时验证 json 文件?可以提供一些样品吗?
-
@Veeram 是的,我想在查询时进行验证。
-
@Veeram 我在问题中添加了一些代码。
标签: json mongodb jsonschema