文档菜单
文档首页
/
MongoDB 手册
/ /

修改模式验证

本页内容

  • 关于此任务
  • 步骤
  • 创建带有验证的集合。
  • 修改验证模式。
  • 结果
  • 插入一个无效文档
  • 插入一个有效文档
  • 处理之前有效的但现在不再有效的文档
  • 了解更多

在将模式验证添加到集合后,您可以在任何时候修改验证规则。例如,您可能决定

  • users 集合中不再需要电子邮件地址。

  • password 字段的最低长度从8个字符增加到12个。

要修改集合的模式验证,请使用collMod 命令,并在 validator 对象中指定更新的验证。

您可以修改模式验证的所有组件,包括其规则、验证级别和验证操作。

如果您更新集合的验证规则,则可能在验证更改之前插入的文档可能不再有效。MongoDB如何处理这些无效文档取决于您的 validationLevel。默认情况下,MongoDB将对所有文档执行验证检查,无论它们何时插入。

以下过程创建了一个带有验证规则的集合,然后修改了这些规则。

1

创建一个具有验证规则的 users 集合

db.createCollection("users", {
validator: {
$jsonSchema: {
bsonType: "object",
required: [ "username", "password" ],
properties: {
username: {
bsonType: "string",
description: "must be a string and is required"
},
password: {
bsonType: "string",
minLength: 8,
description: "must be a string at least 8 characters long, and is required"
}
}
}
}
} )
2

运行以下 collMod 命令,将 password 字段的 minLength 从 8 改为 12

db.runCommand( { collMod: "users",
validator: {
$jsonSchema: {
bsonType: "object",
required: [ "username", "password" ],
properties: {
username: {
bsonType: "string",
description: "must be a string and is required"
},
password: {
bsonType: "string",
minLength: 12,
description: "must be a string of at least 12 characters, and is required"
}
}
}
}
} )

提示

您还可以使用 collMod 命令向未使用验证创建的现有集合添加验证。

以下部分显示了在这些场景中更新的验证结果

  • 当您插入一个无效文档时。

  • 当您插入一个有效文档时。

  • 当由于验证规则更改,之前有效的文档变得无效时。

以下操作尝试插入一个无效文档。该文档无效,因为密码字段的长度为10个字符,而最小长度为12

db.users.insertOne(
{
"username": "salesAdmin01",
"password": "kT9$j4wg#M"
}
)

MongoDB返回以下错误

MongoServerError: Document failed validation
Additional information: {
failingDocumentId: ObjectId("62be0adb73c105dde9231299"),
details: {
operatorName: '$jsonSchema',
schemaRulesNotSatisfied: [
{
operatorName: 'properties',
propertiesNotSatisfied: [
{
propertyName: 'password',
description: 'must be a string of at least 8 characters, and is required',
details: [
{
operatorName: 'minLength',
specifiedAs: { minLength: 12 },
reason: 'specified string length was not satisfied',
consideredValue: 'kT9$j4wg#M'
}
]
}
]
}
]
}
}

以下操作插入了一个有效文档,其中密码字段至少有12个字符长

db.users.insertOne(
{
"username": "salesAdmin01",
"password": "8p&SQd7T90$KKx"
}
)

考虑以下文档,该文档对第一个版本的架构验证是有效的,但对第二个版本不是

db.users.insertOne(
{
"username": "salesAdmin02",
"password": "i8U60*VyL8"
}
)

文档的密码字段为10个字符。第一个版本的架构验证要求至少8个字符,这意味着该文档是有效的。然而,在更新验证以要求密码至少为12个字符后,该文档不再有效。

当架构验证的变化导致以前有效的文档变得无效时,新的无效文档仍然保留在集合中。

MongoDB处理新无效文档的方式取决于模式中的validationLevel。此示例中的模式验证使用默认的validationLevel,即strict,这意味着文档必须符合新的验证规则。MongoDB在每次文档更新时都会检查验证。

如果更新的模式验证的validationLevelmoderate,则该文档不需要符合新的验证规则。

后退

查看现有规则