如果您正在使用Mongo版本3.6,则可以在服务器端使用$jsonSchema
启用模式验证。
我们更新/插入的每个文档都将根据验证模式进行验证,如果验证失败,将抛出错误并且文档上不会进行任何修改。
示例node
集合模式。
{
_id : string,
parent : [string, null],
children : string[2]
}
验证模式(schema)
db.createCollection("node", {
validator: {
$jsonSchema: {
bsonType: "object",
required: [ "_id" ],
properties: {
parent: {
bsonType: ["string", "null"],
description: "must be a string"
},
children: {
bsonType: ["array"],
items : { bsonType: ["string"] },
minItems: 0,
maxItems: 2,
description: "must be a array of string and max is 2"
}
}
}
}
});
插入[使用有效文档]
> db.node.insert( { _id: "Books", children: [ "Programming" ], parent: null } )
WriteResult({ "nInserted" : 1 })
> db.node.insert( { _id: "Programming", children: [ "Databases", "Languages" ], parent: "Books" } )
WriteResult({ "nInserted" : 1 })
> db.node.insert( { _id: "Languages", children: [ ], parent: "Programming" } )
WriteResult({ "nInserted" : 1 })
> db.node.insert( { _id: "Databases", children: [ "MongoDB", "dbm" ], parent: "Programming" } )
WriteResult({ "nInserted" : 1 })
> db.node.insert( { _id: "MongoDB", children: [ ], parent: "Databases" } )
WriteResult({ "nInserted" : 1 })
> db.node.insert( { _id: "dbm", children: [ ], parent: "Databases" } )
WriteResult({ "nInserted" : 1 })
>
查找
> db.node.find()
{ "_id" : "Books", "children" : [ "Programming" ], "parent" : null }
{ "_id" : "Programming", "children" : [ "Databases", "Languages" ], "parent" : "Books" }
{ "_id" : "Languages", "children" : [ ], "parent" : "Programming" }
{ "_id" : "Databases", "children" : [ "MongoDB", "dbm" ], "parent" : "Programming" }
{ "_id" : "MongoDB", "children" : [ ], "parent" : "Databases" }
{ "_id" : "dbm", "children" : [ ], "parent" : "Databases" }
插入无效文档[子元素大小 > 2]
> db.node.insert({_id : "1", children : ["c1", "c2", "c3"], parent : "p1"})
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 121,
"errmsg" : "Document failed validation"
}
})
>
插入数据失败,原因是验证错误。
更新操作 - 尝试为 _id 为 Databases 的记录添加第三个子节点,结果由于验证错误而失败。
> db.node.updateOne( { _id: "Databases"}, {$push : {children: [ "Oracle" ]}} )
2018-02-25T21:00:08.087+0530 E QUERY [thread1] WriteError: Document failed validation :
WriteError({
"index" : 0,
"code" : 121,
"errmsg" : "Document failed validation",
"op" : {
"q" : {
"_id" : "Databases"
},
"u" : {
"$push" : {
"children" : [
"Oracle"
]
}
},
"multi" : false,
"upsert" : false
}
})
WriteError@src/mongo/shell/bulk_api.js:466:48
Bulk/mergeBatchResults@src/mongo/shell/bulk_api.js:846:49
Bulk/executeBatch@src/mongo/shell/bulk_api.js:910:13
Bulk/this.execute@src/mongo/shell/bulk_api.js:1154:21
DBCollection.prototype.updateOne@src/mongo/shell/crud_api.js:572:17
@(shell):1:1
>
请参考
schema-validation 和
jsonSchema 获取更多选项,将验证添加到现有集合并处理验证失败。