简体   繁体   English

如何验证mongodb嵌入式文档

[英]how to validate mongodb embedded document

MongoDB 3.2 has this nice validation feature . MongoDB 3.2具有这个很好的验证功能 However, in this doc it only shows me how to do the validation on first level fields. 但是,在本文档中,它只显示了如何在第一级字段上进行验证。 If I have the following embedded document to insert, how could I set the validation rule? 如果我要插入以下嵌入式文档,我该如何设置验证规则?

{"name": {
          "first_name": "xx",
          "last_name": "yy"
         }
}

I've tried the following but it doesn't work, 我尝试了以下但它不起作用,

db.createCollection( "name_collection",
    { validator: { $and:
        [
            {name.first_name: {$type: "string"}},
            {name.last_name: {$type: "string"}}
        ]
    }
)

Thanks in advance. 提前致谢。

Here are the test codes, it works well 这是测试代码,效果很好

> db.createCollection('name', {validator: {$and: [{"name.first_name": {$type: 'string'}}, {"name.last_name": {$type: 'string'}}]}})
{ "ok" : 1 }

It seems you should add "" to name.last_name , 看来你应该在name.last_name添加""

Test it with valid data 用有效数据测试它

> db.name.insert({name: {first_name: 'xx', last_name: 'yy'}})
WriteResult({ "nInserted" : 1 })

Test it with invalid data 用无效数据测试它

> db.name.insert({name: {first_name: 'xx', last_name: 3}})
WriteResult({
        "nInserted" : 0,
        "writeError" : {
                "code" : 121,
                "errmsg" : "Document failed validation"
        }
})

> db.name.find()
{ "_id" : ObjectId("56e8b644f33ed6e7f3c57f90"), "name" : { "first_name" : "xx",
"last_name" : "yy" } }

Well you have couple errors in your code snippet. 那么你的代码片段中有几个错误。

Your db.createCollection doesn't have matching braches. 您的db.createCollection没有匹配的braches。 It should look like 应该是这样的

db.createCollection("name_collection", {
  validator: { $and:[
    {'name.first_name': {$type: "string"}},
    {'name.last_name': {$type: "string"}}
  ]}
})

To verify if validation is working or not, try inserting partial data 要验证验证是否有效,请尝试插入部分数据

 db.name_collection.insert({name:{first_name:0, last_name:0}})

See I'm just assigning numeric value to first_name and last_name so validation should fail. 请参阅我只是将数值赋给first_name和last_name,因此验证失败。

After execution of above query, It gives following error. 执行上述查询后,它会出现以下错误。

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

But if I assign text as pasted below, insertion should succeed which does. 但是,如果我将文本指定为粘贴在下面,插入应该成功。

db.name_collection.insert({name:{first_name:'f_name', last_name:'l_name'}})

Result: 结果:

WriteResult({ "nInserted" : 1 })

Hope this is what are you looking. 希望这就是你在寻找什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM