Refactor some of couch db code