Неудачная проверка со схемой MongoDB

#mongodb

#mongodb

Вопрос:

Используя MongoDB v3.6.2, я пытаюсь разработать проверку схемы (которая в конечном итоге будет содержать больше значений, чем описано ниже). Мой текущий макет имеет следующую структуру:

Схема

 db.createCollection("Products", {
    validator: {
        $jsonSchema: {
            bsonType: "object",
            required: ["ProductId",
                       "ProductName",
                       "Bonus.PremiumRate",
                       "Bonus.InterestRate",
                       "SurrChargeRates.First",
                       "SurrChargeRates.Second",
                       "SurrChargeRates.Third"],
            properties: {
                "ProductId": {
                    bsonType: "int",
                    description: "Must be a numerical representation of ID"
                },
                "ProductName": {
                    bsonType: "string",
                    description: "Must be a string representation of Product Name"
                },
                "Bonus.PremiumRate": {
                    bsonType: "decimal",
                    description: "Must be a decimal representation of Premium Rate Bonus"
                },
                "Bonus.InterestRate": {
                    bsonType: "decimal",
                    description: "Must be a decimal representation of Interest Rate Bonus"
                },
                "SurrChargeRates.First": {
                    bsonType: "decimal",
                    description: "Must be a decimal representation of First Surrender Charge Rate"
                },
                "SurrChargeRates.Second": {
                    bsonType: "decimal",
                    description: "Must be a decimal representation of Second Surrender Charge Rate"
                },
                "SurrChargeRates.Third": {
                    bsonType: "decimal",
                    description: "Must be a decimal representation of Third Surrender Charge Rate"
                }
            }
        }
    },
    validationLevel: "strict",
    validationAction: "error"
});
  

Это принимается MongoDB и успешно создает коллекцию и проверку. Однако, когда я пытаюсь вставить документ, я сталкиваюсь с кодом ошибки 121, Document failed validation .

insert В настоящее время я пытаюсь выполнить следующее:

Вставить

 db.Products.insert({
    "ProductId": NumberInt(1), 
    "ProductName": "Product Name",
    "Bonus.PremiumRate": NumberDecimal("0.3"),
    "Bonus.InterestRate": NumberDecimal("0.5"),
    "SurrChargeRates.First": NumberDecimal("0.1"),
    "SurrChargeRates.Second": NumberDecimal("0.1"),
    "SurrChargeRates.Third": NumberDecimal("0.1")
});
  

Я также пробовал это, insert отрицая все NumberInt и NumberDecimal теги, без изменений. Кроме того, настройка validationAction: "warn" позволяет вставлять документ, но не является желаемой функциональностью. Аналогично с удалением всех элементов из required объекта.

В чем на данный момент проблема с этим дизайном схемы?

Ответ №1:

Попробуйте выполнить следующую команду:

 db.Products.insert({
    "ProductId": NumberInt(1), 
    "ProductName": "Product Name",
    "Bonus" : {
        "PremiumRate": NumberDecimal("0.3"),
        "InterestRate": NumberDecimal("0.5")
    },
    "SurrChargeRates":{
        "First": NumberDecimal("0.1"),
        "Second": NumberDecimal("0.1"),
        "Third": NumberDecimal("0.1")
    }
});
  

Причиной сбоя является точечная нотация. Subdocuments должно быть вставлено, как указано выше.

Комментарии:

1. Черт возьми! Это сработало отлично. Я предполагал, что точечная нотация будет работать из-за того, что она использовалась при построении схемы. Спасибо!