繁体   English   中英

使用jsonSchema进行Mongo 3.6调试验证

[英]Mongo 3.6 debug validation using jsonSchema

我正在关注mongodb大学的课程,以学习3.6版本中的新功能,而且我无法解决为什么我的验证器无效。

这就是我创建集合的方式:

db.getSiblingDB("TSA").createCollection("claims", {
    validator: {
        $jsonSchema: {
            bsonType: "object",
            properties: {
                _id: { },
                airportCode: { type: "string", minLength: 3 },
                airportName: { type: "string" },
                airlineName: { type: "string", minLength: 5 },
                claims: {
                    bsonType: "object",
                    properties: {
                        itemCategory: { bsonType: "array", maxItems: 3 },
                        amount: { type: "string", pattern: "^\$.*" }
                    }
                }
            },
            required: ["airportCode", "airlineName", "claims"],
            additionalProperties: false
        }
    }
})

然后,我尝试插入此对象:

db.getSiblingDB("TSA").claims.insertOne({
    "airportCode": "ABE",
    "airportName": "Lehigh Valley International Airport, Allentown",
    "airlineName": "MongoAir",
    "claims": {
        "claimType": "Property Damage",
        "claimSite": "Checked Baggage",
        "itemCategory": [ "Sporting Equipment & Supplies" ],
        "amount": "$180.00"
    }
})

收到以下错误:

WriteError({
    "index" : 0,
    "code" : 121,
    "errmsg" : "Document failed validation",
    "op" : {
        "_id" : ObjectId("5a705318d3d6c18337f07282"),
        "airportCode" : "ABE",
        "airportName" : "Lehigh Valley International Airport, Allentown",
        "airlineName" : "MongoAir",
        "claims" : {
            "claimType" : "Property Damage",
            "claimSite" : "Checked Baggage",
            "itemCategory" : [
                    "Sporting Equipment & Supplies"
            ],
            "amount" : "$180.00"
        }
    }
})

我的问题是,有没有办法调试验证器,如“属性X必须是Y类型”而不是获得通用的“文档验证失败”?

从MongoDB 3.6开始,没有反馈机制可以在服务器端检查期间通知文档的哪一部分验证失败。 相应的功能请求已打开: SERVER-20547:公开操作未通过文档验证的原因 目前,如果需要详细的反馈,应由程序代码执行自己的验证。

如果使用正则表达式模式字符串,则反斜杠本身也必须进行转义:

db.getSiblingDB("TSA").createCollection("claims", {
    validator: {
        $jsonSchema: {
            bsonType: "object",
            properties: {
                _id: { },
                airportCode: { type: "string", minLength: 3 },
                airportName: { type: "string" },
                airlineName: { type: "string", minLength: 5 },
                claims: {
                    bsonType: "object",
                    properties: {
                        itemCategory: { bsonType: "array", maxItems: 3 },
                        amount: { type: "string", pattern: "^\\$.*" }
                    }
                }
            },
            required: ["airportCode", "airlineName", "claims"],
            additionalProperties: false
        }
    }
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM