How to properly decouple MongoDB

I'm rather new to web development all together. I'm trying to get a node.js/express/mongo project off the ground. I'm coming from a C/C++ background, and the module organization paradigms seem a little strange to me.

Currently, in my server.js, I create, connect, and initialize my mongoDB object using mongoose, then pass around this object query, insert ect on it. Doesn't seem like something I should be doing inside server.js.

Is the proper way to loosely couple Mongo from my project by creating a separate module (ex. database) where I do all the initialization, options, ect, and return a mongodb instance through this new module?

I've never undertaken a project of this size (or type) before, and just don't know how to best organize everything.. Any advice from those people much more experienced than me would be appreciated

Many ways to do it. Here's some ideas.

Yes, you'll want to have a routing/handlers setup of some kind so that different modules have the ability to call different services and/or decouple.

Below is a fairly standard node.js / express structure:

├── server.js
├── config
│   ├── development
│   ├── production
│   └── staging
├── handlers
│   ├── customers.js
│   └── stores.js
├── node_modules
│   ├── assert
│   ├── ejs
│   ├── express
│   ├── forever
│   ├── mongodb
│   └── mongoskin
├── package.json
├── README.md

then in server.js, you can import your handlers like so:

// import route handlers
var customers = require('./handlers/customers'),
    stores = require('./handlers/stores');

and then inside your handlers, you'll be able to declare functions:

exports.addCustomer = function(req, res) {
    // ....
};

which in server.js you can use for routing:

app.post('/customers/add/:id, metrics.addCustomer);

so then you've got a basic framework. Just defining the database connections outside of the exports.XXX functions in the handler files is fine because those functions will have access, but not anything in server.js so you won't pollute your namespace.

var url = config.user +":"
        + config.pass +"@"
        + config.host +"/"
        + config.database;

var mongo = require('mongoskin').db(url);

where you might load the config object from a JSON file.

hope that helps.