指定 JSON 架构验证

JSON Schema 是一个词汇表,允许您注释和验证 JSON 文档。您可以使用 JSON 模式以人类可读的格式为您的字段指定验证规则。

语境

MongoDB 支持 JSON Schema 草案 4,包括核心规范验证规范, 有一些差异。有关详细信息,请参阅扩展遗漏。

有关 JSON 模式的更多信息,请参阅官网。

限制

您不能为以下内容指定架构验证:

步骤

在此示例中,您创建了一个students包含验证规则的集合,并在您尝试插入无效文档后观察结果。

  1. 创建一个带有验证的集合

    创建一个students集合并使用$jsonSchema 运算符设置模式验证规则。例如:

    db.createCollection("students", {
       validator: {
          $jsonSchema: {
             bsonType: "object",
             title: "Student Object Validation",
             required: [ "address", "major", "name", "year" ],
             properties: {
                name: {
                   bsonType: "string",
                   description: "'name' must be a string and is required"
                },
                year: {
                   bsonType: "int",
                   minimum: 2017,
                   maximum: 3017,
                   description: "'year' must be an integer in [ 2017, 3017 ] and is required"
                },
                gpa: {
                   bsonType: [ "double" ],
                   description: "'gpa' must be a double if the field exists"
                }
             }
          }
       }
    } )
    

    [TIP]

    用标题和描述字段阐明规则

    当规则不是很清楚时,您可以使用title和字段来提供验证规则的解释。description当文档验证失败时,MongoDB 会在错误输出中包含这些字段。

  2. 确认验证可防止无效文档

    以下插入操作失败,因为gpavalidator需要double.

    db.students.insertOne( {
       name: "Alice",
       year: Int32( 2019 ),
       major: "History",
       gpa: Int32(3),
       address: {
          city: "NYC",
          street: "33rd Street"
       }
    } )
    

    该操作返回此错误:

    MongoServerError: Document failed validation
    
    Additional information: {
      failingDocumentId: ObjectId("630d093a931191850b40d0a9"),
      details: {
        operatorName: '$jsonSchema',
        title: 'Student Object Validation',
        schemaRulesNotSatisfied: [
          {
            operatorName: 'properties',
            propertiesNotSatisfied: [
              {
                propertyName: 'gpa',
                description: "'gpa' must be a double if the field exists",
                details: [
                  {
                    operatorName: 'bsonType',
                    specifiedAs: { bsonType: [ 'double' ] },
                    reason: 'type did not match',
                    consideredValue: 3,
                    consideredType: 'int'
                  }
                ]
              }
            ]
          }
        ]
      }
    }
    
  3. 插入有效文档

    gpa字段更改为双精度后插入成功:

    db.students.insertOne( {
       name: "Alice",
       year: NumberInt(2019),
       major: "History",
       gpa: Double(3.0),
       address: {
          city: "NYC",
          street: "33rd Street"
       }
    } )
    
  4. 查询有效文件

    要确认文档已成功插入,请查询 students集合:

    db.students.find()
    

    MongoDB 返回插入的文档:

    [
      {
        _id: ObjectId("62bb413014b92d148400f7a5"),
        name: 'Alice',
        year: 2019,
        major: 'History',
        gpa: 3,
        address: { city: 'NYC', street: '33rd Street' }
      }
    ]
    

附加信息

您可以将 JSON 模式验证与查询运算符验证结合起来。

例如,考虑sales具有此架构验证的集合:

db.createCollection{ "sales", {
  validator: {
    "$and": [
      // Validation with query operators
      {
        "$expr": {
          "$lt": ["$lineItems.discountedPrice", "$lineItems.price"]
        }
      },
      // Validation with JSON Schema
      {
        "$jsonSchema": {
          "properties": {
            "items": { "bsonType": "array" }
          }
        }
      }
    ]
  }
}

前面的验证对 sales集合中的文档强制执行这些规则:

  • lineItems.discountedPrice必须小于lineItems.price。此规则是使用$lt运算符指定的。
  • items字段必须是一个数组。此规则使用 指定 $jsonSchema

学到更多

参见

原文:Specify JSON Schema Validation

译者:景圣

Copyright © 上海锦木信息技术有限公司 all right reserved,powered by Gitbook文件修订时间: 2023-09-01 17:10:26

results matching ""

    No results matching ""