mongoengine icon indicating copy to clipboard operation
mongoengine copied to clipboard

Document inherited from DynamicDocument throws ValidationError on EmbeddedDocument field

Open abhiman24 opened this issue 7 years ago • 5 comments

Document inherited from DynamicDocument throws Validation Error: Invalid embedded document instance provided to an EmbeddedDocumentField.

class MyEmbDoc(EmbeddedDocument):
    emb_field = StringField()

class MyDoc(DynamicDocument):
   emb_doc = EmbeddedDocumentField(MyEmbDoc, )

creating an instance of MyDoc from data in the form:

data_dict = { "emb_doc": {"emb_field": "foo"} } using MyDoc(**data_dict) will throw a "ValidationError (MyDoc:None) (Invalid embedded document instance provided to an EmbeddedDocumentField: ['emb_doc'])",

However, the same MyDoc class if inherited from Document class does not have this issue. Debugging shows that the issue lies in BaseDocument init method:

if self._dynamic: dynamic_data = {} for key, value in values.items(): if key in self._fields or key == '_id': setattr(self, key, value) elif self._dynamic: dynamic_data[key] = value else: FileField = _import_class('FileField') for key, value in values.items(): if key == '__auto_convert': continue key = self._reverse_db_field_map.get(key, key) if key in self._fields or key in ('id', 'pk', '_cls'): if __auto_convert and value is not None: field = self._fields.get(key) if field and not isinstance(field, FileField): **value = field.to_python(value)** setattr(self, key, value) else: self._data[key] = value field.to_python(value) calls the _from_son method that casts the nested dictionary into an object of class MyEmbDoc for instances of Document subclasses but not for those of DynamicDocument.

abhiman24 avatar Jun 08 '18 19:06 abhiman24

I am also suffering from this issue! Any guidance would be very appreciated. I am able to re-produce the results above.

CameronJRAllan avatar Jun 26 '18 14:06 CameronJRAllan

Any updates on this? I've encountered the same problem and haven't found any solution/suggestion yet. @CameronJRAllan @abhiman24 @rozza @bagerard please, could you advice on this. Thanks on advance.

UPD:

Solved this by using document.objects.insert(data_dict) Though it isn't a good solution since I'm skipping validation in this case. Still, can't understand why in case of DynamicDocument we can't use dict for EmbeddedDocument field.

predatorhmo avatar Apr 28 '20 09:04 predatorhmo

I am also having this issue. Is this a bug?

timkeeler avatar Aug 06 '20 00:08 timkeeler

I am still facing issues with this. Any solutions?

wagnerdelima avatar Jul 22 '21 13:07 wagnerdelima

I also have the same problem, and then use from_json to build the instance, it works. such as: MyDoc.from_json(json.dumps(data_dict))

yuhai94 avatar Jun 10 '22 02:06 yuhai94