在mongo中验证数据的最佳方法是什么? [英] What is the best way to validate data in mongo?
问题描述
验证插入或更新到MongoDB中的数据的最佳方法是什么?是否编写某种服务器验证的Java代码进行验证?
What's the best way to validate data being inserted or updated into MongoDB? Is it to write some sort of server executed Javascript code that does the validation?
推荐答案
从 MongoDB 3.2 开始,他们添加了幻灯片).
Starting from MongoDB 3.2 they added document validation (slides).
您可以使用 validator 为每个集合指定验证规则.使用几乎所有mongo查询运算符($geoNear
,$near
,$nearSphere
,$text
和$where
除外)的选项.
You can specify validation rules for each collection, using validator option using almost all mongo query operators (except $geoNear
, $near
, $nearSphere
, $text
, and $where
).
要使用验证器创建新集合,请使用:
To create a new collection with a validator, use:
db.createCollection("your_coll", {
validator: { `your validation query` }
})
要将验证器添加到现有集合中,可以添加验证器:
To add a validator to the existing collection, you can add the validator:
db.createCollection("your_coll", {
validator: { `your validation query` }
})
验证仅在插入/更新时起作用,因此,当您在旧集合上创建验证器时,先前的数据将不被验证(您可以为先前的数据编写应用程序级验证).您还可以指定 validationLevel 和 validationAction 来说明如果文档未通过验证会发生什么情况
Validation work only on insert/update, so when you create a validator on your old collection, the previous data will not be validated (you can write application level validation for a previous data). You can also specify validationLevel and validationAction to tell what will happen if the document will not pass the validation.
如果您尝试使用无法通过验证的内容插入/更新文档(并且未指定任何奇怪的validationLevel/action),那么您会在writeResult
上收到错误提示(可悲的是,该错误无法告诉您什么)失败,并且您仅获得默认的validation failed
):
If you try to insert/update the document with something that fails the validation, (and have not specified any strange validationLevel/action) then you will get an error on writeResult
(sadly enough the error does not tell you what failed and you get only default validation failed
):
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 121,
"errmsg" : "Document failed validation"
}
})
这篇关于在mongo中验证数据的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!