Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb native validation for embedded documents

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?

like image 248
asgs Avatar asked Mar 13 '26 18:03

asgs


1 Answers

First thing null, true and false should not be passed as strings, false passed as the string will evaluate to true only.

Solution No need of "$type" : null validator, just "$exists" : false is enough for your case, The following validation will work for you

"validator" : {
        "$or" : [
            {
                "user" : {
                    "$exists" : false,
                }
            },
            {
                "user.name" : {
                    "$type" : "string",
                    "$exists" : true
                }
            }
            ]
}
like image 166
daemon24 Avatar answered Mar 16 '26 06:03

daemon24



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!