Accessing document fields on database delete trigger

We upload user pictures into S3 and store the file on user_id folder (partition key) and each file has a unique name on that folder. When a document is deleted I need the user_id and file name pairs from the deleted object to continue clean up on S3. But I can’t access fullDocument on delete triggers, any workaround for this? I don’t prefer to execute a user initiated function since client’s connection is not reliable.

Hi @ilker_cam,

Welcome to MongoDB community.

You are correct that delete trigger cannot access the full document object.

I want to offer you a workaround/trick that have worked for me in the past.

Port your delete trigger into an update trigger with fullDocument enabled and filter only updates where updated field is a ttl expired field . (Eg. deleted flag)

Example :

  "updateDescription.updatedFields.deleted": {
    "$exists": true

Now in your collection define a 0 sec life time ttl index on this new Field :

createIndex({deleted : 1},{expireAfterSeconds : 0});

In your application logic when you need to delete a picture update this field to current time.

This will make the documents delete asap while triggering an update event.
As a result you will get an update event that a delete is on the way with fullDocument and can cleanup the file.

In your application queries make sure to query only objects without the “deleted” flag.

Please let me know if that works.


Thanks a lot! I’ll implement your solution, but a fullDocument on delete trigger would save a lot time :slight_smile:

1 Like

@ilker_cam ,

This is currently not possible as the change event for delete does not contain this information. So changing this is changing MongoDB server behaviour…

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.