I am using document validation in MongoDB which is supposed to validate the datatypes of the attributes of documents which I insert into the users collection. Here are the commands which I have executed in the exact same sequence
> 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"
...});
But as soon as I run the last insertOne command, it fails the document validation and prints the following output.
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
I am trying to figure out what if it is the problem with my validator or the data that I am inserting but couldn't. Any help would be appreciated.
use "number" instead of "int" in your document validation :
run
db.runCommand({
collMod:"users",
validator:{
$and:[
{
"nm":{
$type:"string"
}
},
{
"mob":{
$type:"number"
}
},
]
},
validationAction:"error",
validationLevel:"strict"
})
and it should work fine