Mongo中验证数据的最佳方法是什么?

11

如何最好地验证插入或更新到MongoDB中的数据?是编写一些服务器执行的Javascript代码来进行验证吗?


3
Mongo 3.2将具备验证功能。 - Salvador Dali
6个回答

12

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` }
})

验证只在插入/更新时生效,因此当您在旧集合上创建验证器时,以前的数据将不会受到验证(您可以为之前的数据编写应用级别的验证)。您还可以指定validationLevelvalidationAction,以告知如果文档未通过验证会发生什么。

如果您尝试插入/更新一个未通过验证的内容(并且没有指定任何奇怪的validationLevel/action),那么您将在writeResult上收到一个错误(遗憾的是,错误消息并不会告诉您哪些部分未通过验证,而只显示默认的validation failed):

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

6

MongoDB没有约束或触发器,因此应用程序必须验证数据。

您还可以编写JavaScript脚本,每天检查一次或更多次是否存在无效数据。您可以使用此功能来检查应用程序业务逻辑的质量。


1

我认为你的应用程序处理这种情况是很正常的。如果数据以某种方式无效,请在用户纠正了您检测到的任何错误之前,不要将其添加到数据存储中。


1
从2.4开始,MongoDB在写入MongoDB数据文件时为mongod和mongorestore启用基本的BSON对象验证。这可以防止任何客户端将无效或格式错误的BSON插入到MongoDB数据库中。 来源:http://docs.mongodb.org/manual/release-notes/2.4/

1

从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
} )

0

我刚开始在基于Zend Framework的应用程序中使用MongoDB和PHP。

我为每个MongoDB集合创建了一个对象(例如,User.php映射到用户集合)。每个对象都知道它映射到哪个集合,以及需要哪些字段。它还知道应该对每个字段应用哪些过滤器(Zend_Filter_Input)和验证器(Zend_Validate)。在执行MongoDB insert()或save()之前,我运行$object->isValid(),它会执行所有验证器。如果它们全部通过isValid()将返回true,然后我继续运行insert()或save(),否则我显示错误。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接