如何最好地验证插入或更新到MongoDB中的数据?是编写一些服务器执行的Javascript代码来进行验证吗?
如何最好地验证插入或更新到MongoDB中的数据?是编写一些服务器执行的Javascript代码来进行验证吗?
从MongoDB 3.2开始,他们添加了文档验证(幻灯片)。
你可以使用validator选项为每个集合指定验证规则,使用几乎所有mongo查询操作符(除了$geoNear
、$near
、$nearSphere
、$text
和$where
)。
要创建一个带有验证器的新集合,请使用:
db.createCollection("your_coll", {
validator: { `your validation query` }
})
db.createCollection("your_coll", {
validator: { `your validation query` }
})
验证只在插入/更新时生效,因此当您在旧集合上创建验证器时,以前的数据将不会受到验证(您可以为之前的数据编写应用级别的验证)。您还可以指定validationLevel和validationAction,以告知如果文档未通过验证会发生什么。
如果您尝试插入/更新一个未通过验证的内容(并且没有指定任何奇怪的validationLevel/action),那么您将在writeResult
上收到一个错误(遗憾的是,错误消息并不会告诉您哪些部分未通过验证,而只显示默认的validation failed
):
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 121,
"errmsg" : "Document failed validation"
}
})
MongoDB没有约束或触发器,因此应用程序必须验证数据。
您还可以编写JavaScript脚本,每天检查一次或更多次是否存在无效数据。您可以使用此功能来检查应用程序业务逻辑的质量。
我认为你的应用程序处理这种情况是很正常的。如果数据以某种方式无效,请在用户纠正了您检测到的任何错误之前,不要将其添加到数据存储中。
从MongoDB 3.6开始,您还可以使用JSON Schema来表达验证规则。这些检查将在插入/更新时在数据库端发生。
以下是文档中的示例:
validator = {
$jsonSchema: {
bsonType: "object",
required: [ "name", "year", "major", "address" ],
properties: {
name: {
bsonType: "string",
description: "must be a string and is required"
},
year: {
bsonType: "int",
minimum: 2017,
maximum: 3017,
description: "must be an integer in [ 2017, 3017 ] and is required"
},
major: {
enum: [ "Math", "English", "Computer Science", "History", null ],
description: "can only be one of the enum values and is required"
},
gpa: {
bsonType: [ "double" ],
description: "must be a double if the field exists"
},
address: {
bsonType: "object",
required: [ "city" ],
properties: {
street: {
bsonType: "string",
description: "must be a string if the field exists"
},
city: {
bsonType: "string",
description: "must be a string and is required"
}
}
}
}
}
}
db.runCommand( {
collMod: "collectionName",
validator: validator
} )
我刚开始在基于Zend Framework的应用程序中使用MongoDB和PHP。
我为每个MongoDB集合创建了一个对象(例如,User.php映射到用户集合)。每个对象都知道它映射到哪个集合,以及需要哪些字段。它还知道应该对每个字段应用哪些过滤器(Zend_Filter_Input)和验证器(Zend_Validate)。在执行MongoDB insert()或save()之前,我运行$object->isValid(),它会执行所有验证器。如果它们全部通过isValid()将返回true,然后我继续运行insert()或save(),否则我显示错误。