Implement toDBObject() and fromDBObject() methods + misc refactorings.