0

How can I validate that my desc field is required and my category field is optional?

class Mydoc(Document):

    structure = {
        "name": unicode,
        "items": [{
             "category": int,
             "desc": unicode
        }]
    }

 required_fields = ["name", "items", "items.desc"] # Error: items has no attribute 
                                                   # desc, it is a list not a dict.

How can I validate the categories inside the list?

UPDATE

https://groups.google.com/forum/?fromgroups=#!topic/mongokit/GP5AgaMG6T4

danielrvt
  • 10,177
  • 20
  • 80
  • 121

1 Answers1

2

The tricky point here is that we do not know how many items there are. Mongokit doesn't allow you to specify a nested object as required because it could potentially be very slow if you have many items.

So, in short, mongokit doesn't allow required_fields and default_values in nested objects.

However, Mongokit is very light and can be customized very easily if needed:

class MyDoc(Document):
    structure = {
        "name": unicode,
        "items": [{
             "category": int,
             "desc": unicode
        }]
    }

    def validate(self, *args, **kwargs):
        super(MyDoc, self).validate(*args, **kwars)
        for item in self["items"]:
            assert item["desc"], "desc is required: %s" % item
martin clayton
  • 76,436
  • 32
  • 213
  • 198
Namlook
  • 181
  • 11