staticvariablecannot
staticvariablecannot

Reputation: 53

Deleting a Reference in a MongoEngine ListField?

I have Mongoengine ORM that maps the following relationship, (simplified):

class UserInfo(mg.Document):
    username = mg.StringField()
    allcharacters = mg.ListField(mg.ReferenceField("Character"))
    pass

class Character(mg.Document):
    charid = mg.IntField()
    pass

A User refers to an array of references to Character's. The problem is that when I access the User's allcharacter array and delete a reference:

for x in db.UserInfo.objects(username = session["user"])[0].allcharacters:
    if x.charid == someint:
        x.delete()

The document in question gets deleted but the reference in the array remains, pointing to a document that no longer exists.

I tried to

allcharacters = mg.ListField(
    mg.ReferenceField("Character"), reverse_delete_rule=mg.CASCADE)

but that seems to do nothing.

How do I delete the entry in the ListField of an ListField(ReferenceField) in Mongoengine?

Upvotes: 1

Views: 875

Answers (1)

staticvariablecannot
staticvariablecannot

Reputation: 53

To guide future generations: In order to delete the reference element from an array once the actual reference has been deleted, requires using the $pull operation.

char = db.Character.objects()[0]
objid = char.pk
char.delete()

user = db.UserInfo.objects().update_one(pull__allcharacters=objid)

Get a variable that points to the specific reference you want to delete. Use the .pk attribute to get it's ObjectId. You can now delete the document. To delete the reference in the array within the document, it's a pull query such that if the objid is in the array of allcharacters

May the future generation find this a solace.

Upvotes: 3

Related Questions