Как исправить ошибку проверки документа в Mongodb? - PullRequest
0 голосов
/ 30 октября 2019

Я создал следующую коллекцию (создание которой прошло успешно)

db.createCollection("Company", { "validator": { "$jsonSchema": {
    "bsonType":"object",
    "required":["city_name","city","street_name","building_number","budget","Department"],
    "properties":{ "city_name":{ "bsonType":"string",
                            "description":"name of city" },
                   "city":{ "bsonType":"string",
                            "description":"City" },
                   "street_name":{ "bsonType":"string",
                                          "description" :"name of street" },
                   "building_number":{"bsonType":"int",
                                "description":"number of building", minimum: 0, maximum: 500},
                   "budget":{"bsonType":"double",
                                           "description":"budget of company",minimum: 0 },

                   "Department":{ "bsonType":"object",
                               "required":["Department_name","floor_number","Employee"],
                               "properties":{ "Department_name":{"bsonType":"string",
                                                        "description": "name of department" },
                                              "floor_number":{"bsonType":"int",
                                                      "description":"number of floor" },
                                             }},

                    "Employee":{ "bsonType":"object",
                                          "required":["first_name","last_name","DOB","Salary"],
                                          "properties":{"first_name":{"bsonType":"string",
                                                                "description":"Employees first name"},
                                                        "last_name":{"bsonType":"string",
                                                                 "description":"Employees last name"},
                                                        "DOB":{"bsonType":"date",
                                                                   "description":"Date of birth of empployee"},
                                                        "Salary":{"bsonType":"double",
                                                                   "description":"Salary of Employee",minimum: 0},
                                                        "Position":{"bsonType":"string",
                                                                   "description":"Position of employee. Field is not required"}}}}}}});

Я создал набор данных для вставки в эту коллекцию, чтобы проверить проверки


db.Company.insert(
    { "city_name":"Sydney",
       "city":"Sydney",
       "street_name":"Pitt Street",
       "building_number":100,
       "budget": 100000.0,
       "Department":{"department_name":"Google",
                  "floor_number":4,
        "Employee" :{"first_name" : "George",
                     "last_name": "Martin",
                     "DOB": new Date('Dec 26,1981'),  
                     "Salary" : "70000",
                      "Position": "CEO"}}

     });

Однакокогда я запускаю этот скрипт, я получаю сообщение об ошибке

WriteResult({
    "nInserted" : 0,
    "writeError" : {
        "code" : 121,
        "errmsg" : "Document failed validation"
    }
})

К сожалению, Mongodb не очень конкретен в причинах таких ошибок, и я прошел через мой синтаксис и объявления и сам не мог обнаружить любые ошибки, когда явно есть!

Почему я получаю эту ошибку при запуске моего кода? Thankyou

Ответы [ 2 ]

1 голос
/ 30 октября 2019

"Salary" : "70000" - это int, но схема запрашивает double: "Salary":{"bsonType":"double", "description":"Salary of Employee",minimum: 0},.

Я бы рекомендовал использовать псевдоним "bsonType":"number" в своей схеме вместо intdouble 1010 decimal. Поскольку javascript не напечатан, отследить, что используется в вашем коде, может быть очень трудно.

См. Документ: https://docs.mongodb.com/manual/reference/operator/query/type/#available-types

1 голос
/ 30 октября 2019

Попробуйте:

01) Схема:

db.createCollection(
    "Company", 
    {
        "validator": { 
            "$jsonSchema": {
                "bsonType":"object",
                "required":["city_name","city","street_name","building_number","budget","Department"],
                "properties": { 
                    "city_name":{ "bsonType" : "string", "description" : "name of city" },
                    "city":{ "bsonType" : "string", "description" : "City" },
                    "street_name":{ "bsonType" : "string","description" : "name of street" },
                    "building_number": { "bsonType" : "int", "description" : "number of building", minimum: 0, maximum: 500},
                    "budget": { "bsonType" : "double", "description" : "budget of company",minimum: 0 },
                    "Department": { 
                        "bsonType":"object",
                        "required":["Department_name","floor_number","Employee"],
                        "properties": { 
                            "Department_name":{"bsonType":"string", "description": "name of department" },
                            "floor_number":{"bsonType":"int", "description":"number of floor" },
                            "Employee":{ 
                                "bsonType":"object",
                                "required":["first_name","last_name","DOB","Salary"],
                                "properties":{
                                    "first_name":{"bsonType":"string", "description":"Employees first name"},
                                    "last_name":{"bsonType":"string", "description":"Employees last name"},
                                    "DOB":{"bsonType":"date", "description":"Date of birth of empployee"},
                                    "Salary":{"bsonType":"double", "description":"Salary of Employee",minimum: 0},
                                    "Position":{"bsonType":"string", "description":"Position of employee. Field is not required"}
                                }
                            }
                        }
                    },
                }
            }
        }
    }
);

02) Вставка:

db.Company.insert(
{  
    "city_name": "Sydney",
    "city": "Sydney",
    "street_name": "Pitt Street",
    "building_number": NumberInt(100),
    "budget": 100000.0,
    "Department":{
        "Department_name":"Google",
        "floor_number": NumberInt(4),
        "Employee" : {
            "first_name" : "George",
            "last_name": "Martin",
            "DOB": new Date('Dec 26,1981'),  
            "Salary" : 70000.0,
            "Position": "CEO"
        }
    },    
});

Я должен сделать несколько изменений:

  • 'int' поля должны быть NumberInt (число) в команде вставки.
  • Схема была изменена так, чтобы «Сотрудник» былв «Департаменте».
  • Зарплата должна быть двойной.
...