簡體   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