0

My Node.js server code was getting unwieldy and long, so I recently began refactoring functions into separate .js files and bringing them in via requires. eg:

//server.js
var queries = require('./routes/queries');
var authenticate = require('./routes/authenticate');
...

//queries.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
exports.SomeFunctionB = ...
...

//authenticate.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
exports.SomeFunctionA = ...
...

However, now whenever I run my code, Mongoose.connect spits out an error about trying to open an unclosed connection. I understand that this is because I'm calling mongoose.connect in both JS files.

Since I know that Server.js, the Node.js file that actually gets run, require s queries.js before authenticate.js, can I simply leave out the second mongoose.connect?

Perhaps more specifically, is the var mongoose in the queries file the same reference as the var mongoose in the authenticate file?

And if not, how can I test whether or not I need to make that mongoose connection in the first place?

Raven Dreamer
  • 6,940
  • 13
  • 64
  • 101

1 Answers1

0

I'm not sure that monogoose has an API method for that. However, I think that you should not try to connect in different files. Why don't you do this only once. Inside your main file. I don't know if you use any framework, but you may attach the mongoose object to the request and pass it to all your files. Here is an example which uses mongodb native driver, but the idea is well illustrated:

MongoClient.connect('...', function(err, db) {
    if(err) {
        console.log('Sorry, there is no mongo db server running.');
    } else {
        var attachDB = function(req, res, next) {
            req.db = db;
            next();
        };
        app.all('/admin*', attachDB, function(req, res, next) {
            // run your constroller here
        });         
        app.all('/blog/:id', attachDB, function(req, res, next) {
            // run your constroller here
        });
        app.all('/', attachDB, function(req, res, next) {
            // run your constroller here
        });     
        http.createServer(app).listen(config.port, function() {
            console.log(
                'Successfully connected to mongodb://' + config.mongo.host + ':' + config.mongo.port,
                '\nExpress server listening on port ' + config.port
            );
        });
    }
});

So, attachDB is actually a middleware which patches the request object. Once that object is passed for the next middleware it has an access to the mongodb client.

Krasimir
  • 13,306
  • 3
  • 40
  • 55
  • Either I don't understand this, or I don't believe this is quite analogous to my situation. I've a node server which does the connecting, there's not an issue of multiple webpages (/admin, /blog, /, etc.). – Raven Dreamer Sep 06 '13 at 14:29