Is your wrapper open-source and available in NPM? If not, it should be! :)
Re:MongoDB singleton connection in Node.Js
by joshguthrie on Friday April 05, 2013 @09:00AM
(#5498089)
Was thinking about it but never imagined people would actually be interested in it ^^;
I'll clean it up a bit before. It should appear in https://github.com/joshleaves and https://npmjs.org/~joshleaves by the end of the day :)
- Query all collections at startup time and attach them to your singleton so you can just call MongoDbSingleton[collection].find(). This way you only call your collections once and gain lot in speed for subsequent requests.
- Since you are querying all your collections, you might as well use .ensureIndex() by then to make sure your application won't insert two users with the same e-mail.
- Now that you have sane collections, you can rid your application code of one "useless" instruction: give each collection a method that wraps the call to .find() in another function that will perform the .toArray() for you in the background. (This is NOT removing the step, it is merely moving it elsewhere for code readability).
- Play a bit more with your new singleton: you know how to craft a BSON ObjectId from an hexstring? Simple, call "mongodb.BSONPure.ObjectID.createFromHexString()". Okay, too long, why not have a method to wrap that in your singleton?
- All these function (err [, data]) flying around... Why not have a single function that will always be called to check for "err" existence and output error and trace?
I've been using most (if not all) of those tips in my own MongoDb wrapper, both in professionnal apps and side-projets and it's made my MongoDb use much more simpler. Hit me up if you want some more tips ;)