Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
           });
         });
like image 365
pawel Avatar asked Nov 17 '13 15:11

pawel


People also ask

Which method is used to connect from Nodejs to MongoDB?

No-SQL databases allow developers to send and retrieve data as JSON documents, instead of SQL objects. To work with MongoDB in a Node. js app, we can use Mongoose.


2 Answers

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.

like image 81
WiredPrairie Avatar answered Oct 11 '22 16:10

WiredPrairie


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.

like image 25
floatdrop Avatar answered Oct 11 '22 17:10

floatdrop