Search code examples
mongodbvalidationembedded-documents

how to validate mongodb embedded document


MongoDB 3.2 has this nice validation feature. 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.


Solution

  • 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,

    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" } }