I have some legacy MongoDB collection that has a particular field that can be null, a list ([]) and an object with a particular list of fields. I'm trying to implement the basic Document that allows this behavior.
I tried using this approach:
class MyDBEntity(Document):
my_field = GenericEmbeddedDocumentField(
choices=(
MyParticularField,
List
),
default=None,
null=True
)
class MyParticularField(EmbeddedDocument):
# some fields, etc.
Every time I try to use this approach, I get this error:
File "path_to_venv/mongoengine/fields.py", line 837, in to_python
doc_cls = get_document(value["_cls"])
KeyError: '_cls'
My understanding is that MongoEngine should populate _cls field for me, however, it's not there.
If I use a standalone EmbeddedDocumentField, the solution works when the expected object is in entries in the collection:
class MyDBEntity(Document):
my_field = EmbeddedDocumentField(MyParticularField, default=None, null=True)
Obviously, it fails when a list is present.
How should I proceed with this use case, expecting both a list and an object?
Is your list a list of EmbeddedDocuments? If that is the case, you can use an EmbeddedDocumentListField. If not, you can just use a DynamicField, this will accept any value you want. If you want to restrict the type of values you accept, you can use the "clean" function to check the data before saving the document:
And about _cls, if I'm not mistaken, this field only exists when you work with Document inheritance (meta = {'allow_inheritance': True})