Mongodb native validation for embedded documents

81 views
Skip to first unread message

A S Gowri Sankar

unread,
Nov 22, 2017, 2:37:10 PM11/22/17
to mongodb-user
Hello! This is a cross post from Stack Overflow I posted few hours ago.

I'm looking for a way to add a validator to a collection such that an embedded document inside the main Mongo document could be entirely absent or if it's present a few of its attributes must be present.

I played around with the $or operator specifying that the `user` embedded document is not required (with the $exists operator set to false) OR the `name` field of the `user` embedded document is present and of $type `string`.

Apparently I'm not able to insert an empty document {} into such a collection as it throws a "Document failed validation" error.

What's wrong with the usage of query operators used in this validator? Please ask if you need more information. Thank you!

A S Gowri Sankar

unread,
Nov 23, 2017, 6:14:10 AM11/23/17
to mongodb-user
Any pointers on this one? I'm completely clueless with very little documentation and help from SO and IRC channels.

Rhys Campbell

unread,
Nov 23, 2017, 9:36:01 AM11/23/17
to mongodb-user
"validator" : { "$or" : [ { "user" : { "$exists" : "false", "$type" : "null" } }, { "user.name" : { "$type" : "string", "$exists" : "true" } } ] }


Have you tried without the $type: null test?

A S Gowri Sankar

unread,
Nov 23, 2017, 9:56:37 AM11/23/17
to mongodb-user
Yes, Sir. Did try and still get the "Document failed validation" error.

A S Gowri Sankar

unread,
Nov 27, 2017, 6:52:48 AM11/27/17
to mongodb-user
Just got an answer from the SO post and the problem was treating the value of $exists operators as strings, instead of boolean. So it looks like values such as "false", "true" are both treated as boolean true.

I wish Mongodb throws a validation error whenever it encounters such malformed values. Thank you!


On Thursday, November 23, 2017 at 1:07:10 AM UTC+5:30, A S Gowri Sankar wrote:
Reply all
Reply to author
Forward
0 new messages