由于文档验证,插入查询突然失败

时间:2017-01-04 13:12:56

标签: mongodb mongodb-query

我在MongoDB中使用文档验证,它应该验证我插入users集合的文档属性的数据类型。以下是我以完全相同的顺序执行的命令

> db.createCollection("users");
{ "ok" : 1 }

> db.runCommand({
...  collMod: "users",
...  validator: {
...    $and : [
...      { "nm" : { $type : "string" }},
...      { "mob" : { $type : "int" }},
...    ]
...  },
...  validationAction: "error",
...  validationLevel: "strict"
... });
{ "ok" : 1 }

> db.users.insertOne(
  {
...  "nm" : "foo",
...  "eml" : "foo@gmail.com",
...  "mob" : 12345,
...  "isa" : true,
...  "blod" : "O+",
...  "sid" : 1,
...  "cid" : 1,
...  "aid" : 1,
...  "add" : "bar",
...  "dob" : "16-Sep-1992"
...});

但是,只要我运行最后一个insertOne命令,它就会使文档验证失败并输出以下输出。

2017-01-04T18:27:16.824+0530 E QUERY    [main] WriteError: Document failed validation :
WriteError({
    "index" : 0,
    "code" : 121,
    "errmsg" : "Document failed validation",
    "op" : {
        "_id" : ObjectId("586cf12c5a37c6beeeb15940"),
        "nm" : "foo",
        "eml" : "foo@gmail.com",
        "mob" : 12345,
        "isa" : true,
        "blod" : "O+",
        "sid" : 1,
        "cid" : 1,
        "aid" : 1,
        "add" : "bar",
        "dob" : "16-Sep-1992"
    }
});
WriteError@src/mongo/shell/bulk_api.js:469:48
Bulk/mergeBatchResults@src/mongo/shell/bulk_api.js:836:49
Bulk/executeBatch@src/mongo/shell/bulk_api.js:906:13
Bulk/this.execute@src/mongo/shell/bulk_api.js:1150:21
DBCollection.prototype.insertOne@src/mongo/shell/crud_api.js:242:9
@(shell):1:1

我试图弄清楚如果我的验证器或我插入但不能的数据是什么问题。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

在文档验证中使用"number"代替"int"

运行

db.runCommand({
   collMod:"users",
   validator:{
      $and:[
         {
            "nm":{
               $type:"string"
            }
         },
         {
            "mob":{
               $type:"number"
            }
         },

      ]
   },
   validationAction:"error",
   validationLevel:"strict"
})

它应该可以正常工作