Closes document before deleting it to prevent it from reappearing

I saw some issues with the deletions of documents, and so I wanted to fix it. 
Here's my attempt. It works from here in my own app, but you should probably test it yourself.

Have a nice day!