Garbage Collection

No, this is not a post about memory management, but about an actual MongoDb collection called "garbage".

Whenever we present a "delete" button in a web app, we're faced with the problem of what to do once the user chooses to press it. The obvious choice is to simply go ahead, do what the button says, and delete stuff in our database. Possibly after the typical, "Do you really, really want to actually delete your stuff?" dialog.

In many cases this works fine, but ever so often we're faced with a situation where we just know that no matter how much we ask the user to confirm his intentions; he'll ever so often come back and ask where his fabulous party pictures went or how to bring back that blog post he accidentally deleted.

The Flag

The typical option in a database driven application is to add a "deleted" flag to a table. When the user tells us to delete stuff, we just mark his item as deleted instead of actually deleting it. We then have to remember to take that flag into account whenever we query against that table in any part of our app, and all queries gets the added complexity of having to filter by our deleted flag.

The "deleted" flag is pretty much the best solution we'll get when dealing with a relation database where we're (hopefully!) working with normalized data, but when using a document oriented database there's another alternative.

Mongodb is schemaless and instead of normalized data, we work with structured documents. This means that moving a full document from one collection to another is no problem. Get the document from column a, insert it in column b and delete it from column a. Job done.

The Garbage Collection

If we use MongoDB's default ObjectId as the key for our document, we can even move completely different types of documents to the same collection, since ids are unique and collections are schemaless.

In Webpop we have a collection called "garbage" where we dump stuff that gets deleted until someone disposes of it.

Instead of setting a deleted flag on an entry when a user deletes it, we simply move the whole entry to the "garbage" collection. It's now gone from it's normal collection. No queries have to worry about filtering it out, no validations of uniqueness have to consider ghost items in the collection. There's no added complexity when dealing with non-deleted entries.

If the user figures out he deleted the wrong post or got rid of a perfectly fine photo-album, all the data are still there, ready to be moved back to it's own spot.

Next time you need a "deleted" flag in a MongoDB backed app, stop and consider if simply throwing your document in the garbage might be a better idea.

comments powered by Disqus