News for hackers. Stuff that matters.
Re:MongoDB singleton connection in Node.Js by outside1234 on Friday April 05, 2013 @09:12AM (#5498161)
If you are using mongoose, is there a similar advantage to be had or is this handled internally?
Re:MongoDB singleton connection in Node.Js by jameswyse on Friday April 05, 2013 @09:29AM (#5498249)
What I tend to do is create a database file (db.js) which exports an object with getters for mongoose, redis, etc. The getter connects to the db and returns the connection the first time and returns a cached copy on subsequent calls.

One big tip for mongoose is to use the .lean() function on your queries whenever you don't need to use any special mongoose features (statics, virtuals, etc), which returns a standard JS Object instead of a mongoose collection instance. It can be quite a bit faster!

Re:MongoDB singleton connection in Node.Js by latchkey on Friday April 05, 2013 @01:17PM (#5499684)
Even if you use mongoose, you still need to make sure that a connection is successfully made to the database before you try to start using it. This is a blocking operation. The problem is that by default some node libraries (cough redis cough) will cache requests in memory and execute them once the connection is made. This is terrible because if node dies (for example, if mongo fails to connect), all that data is dead.
Re:MongoDB singleton connection in Node.Js by joshguthrie on Friday April 05, 2013 @09:15AM (#5498178)
From what I remember, Mongoose pretty much does the same.

The "Attach each collection to your MongoDbSingleton as MongoDbSingleton[Collection]" trick was actually taken from Mongoose (which uses MongooseSingleton[Model] instead).

Re:MongoDB singleton connection in Node.Js by andypants on Friday April 05, 2013 @09:31AM (#5498268)
Mongoose does the same. Once you're connected to mongodb in your app, all subsequent requires to mongoose will have access to that connection.