OperationError: Could not save document (LEFT_SUBFIELD only supports Object: ancestors.0 not: 7)

django, mongodb, mongoengine, python

Solution

This is mongoengine bug. I created issue for this: https://github.com/MongoEngine/mongoengine/issues/422.

Solutions for now:

Use full reload document before updating (just `reload` don't work, because leave referencies):

obj1 = Organization.objects(username=obj1.username).first()
obj1.descendants = [obj2, obj3]
obj1.save()


obj2 = Organization.objects(username=obj2.username).first()
obj2.descendants = [obj3]
obj2.save()

Use atomic updates instead `save`.

Use `to_dbref` for referencies:

obj1 = Organization(username='kousik')
print obj1.save()
# <Organization: Organization object> #obj1 created

obj2 = Organization(username='chowdhury', ancestors=[obj1.to_dbref()], parents=[obj1.to_dbref()])
print obj2.save()
# <Organization: Organization object> #obj2 created

obj3 = Organization(username='kchowdhury', ancestors=[obj1.to_dbref(), obj2.to_dbref()], parents=[obj2.to_dbref()])
print obj3.save()
# <Organization: Organization object> #obj3 creaed

obj1.descendants = [obj2.to_dbref(), obj3.to_dbref()]
print obj1.save()
# <Organization: Organization object> #obj1 updated

obj2.descendants = [obj3.to_dbref()]
print obj2.save()
# <Organization: Organization object> #obj2 updated

Problem

I have an Organization database in MongoDB. I am trying to save data in that database using `mongoengine`. I am using `Djnago` server. when i am creating the object then its working fine but after editing its giving some error. ``` class Organization(Document): username= StringField() ancestors = ListField(ReferenceField('Organization',dbref=False), default = list) parents = ListField(ReferenceField('Organization',dbref=False),default = list) descendants = ListField(ReferenceField('Organization',dbref=False), default = list) obj1 = Organization(username = 'kousik') obj1.save() <Organization: Organization object> #obj1 created obj2 = Organization(username = 'chowdhury',ancestors = [obj1],parents=[obj1]) obj2.save() <Organization: Organization object> #obj2 created obj3 = Organization(username = 'kchowdhury',ancestors = [obj1,obj2],parents=[obj2]) obj3.save() <Organization: Organization object> #obj3 creaed obj1.descendants = [obj2,obj3] obj1.save() <Organization: Organization object> #obj1 updated obj2.descendants = [obj3] obj2.save() Traceback (most recent call last): File "<pyshell#43>", line 1, in <module> obj2.save() File "C:\Python27\lib\site-packages\mongoengine\document.py", line 267, in save raise OperationError(message % unicode(err)) OperationError: Could not save document (LEFT_SUBFIELD only supports Object: ancestors.0 not: 7) ```

Original source