Trying to DRY up nodejs express app using mongodb

By : kjs3

I'm trying to separate my mongodb code in a nodejs express app and am having troubles understanding how to shuffle things around.

here's a gist of what I have

I've dumbed it down to almost nothing in the middleware. When I start the server, res.myvar is correctly set to "object" in the first request. Every subsequent request fails with res.myvar being "undefined".

I just want to stick the db code in a single place and then be able to use it in my various routes. Am I going about this wrong? All the examples on the mongodb nodejs driver page just make db queries etc. I'm not finding much integrating the whole thing in an express app.

By : kjs3


What I had originally was opening new db connections on every request. I've edited the gist and left the old stuff commented out.

It works now.

Many thanks to Ciaran's blog post It's kinda old but still helped.

By : kjs3

I am writing node-fourm, I have the same problem at beginning. There is a db folder and controller folder in node-fourm, they are seperated now, and I can define method for each collection now. Check the code for detail.

I wrote mongoskin to make it possible.

This video can help you solving your question :)
By: admin