9

im using expressJS and mongoDB and I try to persist my mongodb connection opened in one place to whole app.

How should I do it?

I dont want to open it every time in my every route/model file, which looks like:

moods.js (example file, i have plenty of them, one for every collection)

exports.findAll = function(req, res) {
    db.collection('moods', function(err, collection) {
        collection.find().toArray(function(err, items) {
            res.send(items);
        });
    });
};

 .... some other methods

and main app.js file:

var express = require('express');
var routes = require('./routes');
var mood = require('./routes/moods');


var http = require('http');
var path = require('path');

var app = express();


// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'hjs');
app.use(express.favicon());
...

app.get('/moods', mood.findAll);

....
http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

Now, where should I put this piece of code to exist once and work for my every collection files? I mean to open one coonnection, not opening new every time i want to query my DB.

         var mongodb = require('mongodb');
         var db = new mongodb.Db('xxxx',
           new mongodb.Server('xxxx', 10059, {})
         );
         db.open(function (err, db_p) {
           if (err) { throw err; }
           db.authenticate('xxxx', 'xxxx', function (err, replies) {
             // You are now connected and authenticated.
           });
         });

4 Answers 4

17

You've got several reasonable options. It's really a matter of personal preference.

Create another module that opens the connection and have all other modules use that module:

mongo_connection.js

In that file, you'll put the connection and authentication code. Export the db instance for example:

exports.db = db;

In other files, you could require it:

var connection = require('./mongo_connection.js');
var db = connection.db;

Or, I often create the connection once (in a module), and then pass that to an initialization function in routes:

var users = require('./routes/users.js');
users.initialize(db);

I often do that as there's other common configuration work and settings that I want to provide to the routes:

var initialize = function(app, config) {

};

If you pass the express app instance around, you could set it as well:

app.set('mongo', db);

And then use app.get('mongo') to fetch it.

Sign up to request clarification or add additional context in comments.

Comments

4

You can use express-mongo-db middleware for this. It will create and cache connection to mongodb so you can use it inside findAll through req.db property.

3 Comments

How would this work when there are multiple databases?
@ayan just create multiple instances of express-mongo-db.
@floatdrop: Can you please provide some guidance on how this middleware works with respect to losing connection to mongo server due to there being idle time? One of the issues I've been experiencing is that because of idle time, my express app loses connection to mongodb server. After that, any http request I process through the app doesn't make it through to mongodb. Thanks.
1

If you don't want to use express-mongo-db, you can do pretty much the same thing with:

app.js / server.js

...    
let _db = null;

MongoClient.connect('mongodb://localhost/test', (err, db) => {
    _db = db;
});

app.use(function(req, res, next) {
    res.locals.db = _db;
    next();
});
...

routes/index.js

...
router.get('/', function(req, res) {
    res.locals.db.authenticate('xxxx', 'xxxx', function (err, replies) {
       // You are now connected and authenticated.
    });
});
...

Comments

0

Get db connection in request using express-mongo-db package

In Your App.js

var expressMongoDb = require('express-mongo-db');
app.use(expressMongoDb('your_mongoDB_url'));

In your Other Files(routes etc) Where You Need DB Utilization

router.get('/test', function(req, res){
    req.db.collection("collectionName").find().toArray(function(err, docs){
        console.log(docs);
    });

});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.