pythonmongodbmongoenginelistfield

Deleting EmbeddedDocument with FileField from ListField


In MongoEngine, when deleting an EmbeddedDocument from a ListField which includes a FileField, the referenced file does not get deleted. Currently, I have solved the issue by looping over the whole list field.

for embdoc in doc.embdocs:
    if embdoc.filtered == value:
        embdoc.dfile.delete()
doc.update(pull__embdocs={'filtered': value})

I was wondering if there was a better way to do this.


Solution

  • By default, MongoDB doesn’t check the integrity of your data, so deleting documents that other documents still hold references to will lead to consistency issues.

    You should use ListField with ReferenceFields. ReferenceFields can used with option reverse_delete_rule=mongoengine.PULL or another:

    mongoengine.DO_NOTHING This is the default and won’t do anything. Deletes are fast, but may cause database inconsistency or dangling references.

    mongoengine.DENY Deletion is denied if there still exist references to the object being deleted.

    mongoengine.NULLIFY Any object’s fields still referring to the object being deleted are removed (using MongoDB’s “unset” operation), effectively nullifying the relationship.

    mongoengine.CASCADE Any object containing fields that are refererring to the object being deleted are deleted first.

    mongoengine.PULL Removes the reference to the object (using MongoDB’s “pull” operation) from any object’s fields of ListField (ReferenceField).