pawel
pawel

Reputation: 6136

Handle mongodb connection in expressJS

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.
           });
         });

Upvotes: 9

Views: 6130

Answers (4)

Dev Matee
Dev Matee

Reputation: 5939

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);
    });

});

Upvotes: 0

Beau
Beau

Reputation: 1771

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.
    });
});
...

Upvotes: 1

floatdrop
floatdrop

Reputation: 612

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.

Upvotes: 4

WiredPrairie
WiredPrairie

Reputation: 59763

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.

Upvotes: 17

Related Questions