How to Delete Orphan Files in Parse Server after Updating or Deleting Objects.

Parse Server does not automatically deletes associated file after deleting object or updating it because Parse Server does not know if you are still using those files somewhere. This cause waste of resources If we don’t delete these orphan files manually and the size of database will also grow.

There will be generally 2 cases where we need to delete the files.

  • File is replaced by new file. Now you want to delete the old file.
  • Object is deleted and you no longer need the file. You no longer need the file because the file is only used in that object and nowhere else.

File is replace by a new one

// Delete old post image whenever image is updated
Parse.Cloud.afterSave('Post', (request) => {
    const image = request.object.get('image');
    const imageOriginal = request.original.get('image');

    if (imageOriginal && JSON.stringify(image) !== JSON.stringify(imageOriginal)) {
        // delete image if image has been changed/updated
        try {
            imageOriginal.destroy();
        } catch (error) {
            console.error("Error deleting image " + error.code + ": " + error.message);
        }
    }
});

Object is deleted and file should be also deleted

// Delete post image when post is deleted
Parse.Cloud.afterDelete("Post", (request) => {
    const image = request.object.get('image');
    try {
        image.destroy();
    } catch (error) {
        console.error("Error deleting image " + error.code + ": " + error.message);
    }
});

2 thoughts on “How to Delete Orphan Files in Parse Server after Updating or Deleting Objects.”

Leave a Comment

Your email address will not be published. Required fields are marked *