Darth Plagueis
Darth Plagueis

Reputation: 930

mongoengine OperationError on saving

I'm writing a python script to populate a mongodb database, my models look like the following:

from mongoengine import *
from mongoengine.django.auth import User

class TrackGroup (Document):
    name = StringField(required=True)
    users = ListField(ReferenceField('User'))
    devices = ListField(ReferenceField('Device'))

class Device(Document):
    name = StringField(max_length=50, required=True)
    grp = ListField(ReferenceField(TrackGroup))

class User(User):
    first_name = StringField(max_length=50)
    last_name = StringField(max_length=50)
    grp = ListField(ReferenceField(TrackGroup))

And my script goes like this:

#Create a group
gName = 'group name'
g = TrackGroup(name=gName)
g.users = []
g.devices = []
g.save()

#create a user
u = User.create_user(username='name', password='admin', email='[email protected]')
gRef = g
u.grp = [gRef, ]
u.first_name = 'first'
u.last_name = 'last'
u.save()
gRef.users.append(u)
gRef.save()

#create a device
dev = Device(name='name').save()
gRef = g
dev.grp = [gRef, ]
dev.save()
gRef.devices.append(dev)
gRef.save()     #Problem happens here

The problem happens when I call gRef.save() I get the following error:

raise OperationError(message % unicode(err))
mongoengine.errors.OperationError: Could not save document (LEFT_SUBFIELD only supports Object: users.0 not: 7)

I looked around for a while, and here it says that this means I'm trying to set a filed with an empty key, like this: (The example is from the link above, not mine)

{
    "_id" : ObjectId("4e52b5e08ead0e3853320000"), 
    "title" : "Something", 
    "url" : "http://www.website.org", 
    "" : "", 
    "tags" : [ "international"]
}

I don't know where such a field can come from, but I opened a mongo shell and looked at my documents from the three collections, and I couldn't find such a field.

Note: If I add the device first, the same error occurs while saving the group after adding the user.

Upvotes: 1

Views: 2674

Answers (1)

Jeffery Li
Jeffery Li

Reputation: 565

I had the same error, and this trick work for me:

the_obj_causing_error.reload()
/* make some change */
the_obj_causing_error.price = 5
the_obj_causing_error.save()

just try reload() the object before changing it.

Upvotes: 2

Related Questions