I'm trying to come up with a Mongodb's native validation rule that will validate a document (having an embedded document) such that either the embedded document is not present at all OR if present, it has one or more fields mandatorily present.
I have got an example below. A JSON document has an embedded document user. This user may not exist or when it exists it needs to have a field name mandatorily present.
"validator" : {
"$or" : [
{
"user" : {
"$exists" : "false",
"$type" : "null"
}
},
{
"user.name" : {
"$type" : "string",
"$exists" : "true"
}
}
]
}
And when I try to insert an empty JSON document to my collection testschema like db.testschema.insert({}), I get the standard error below which doesn't tell what is wrong and/or why. This should be possible because my document can either contain an embedded document user with a field name or not contain the embedded document at all.
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 121,
"errmsg" : "Document failed validation"
}
})
Are the operators used inside the validator looking correct?