Handle mongodb connection in expressJS

im using expressJS and mongoDB and I am trying to keep my mongodb connection open in one place for the whole application.

How can I do it?

I don't want to open it every time in every route / model file that looks like this:

moods.js (example file, I have a lot of them, one for each 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 the 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 at once and work for all my collection files? I want to open one connection, but not open it 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. }); }); 
+7
mongodb express
source share
4 answers

You have some reasonable options. This is really a matter of personal preference.

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

 mongo_connection.js 

In this file you will place the connection and authentication code. Export the db instance, for example:

 exports.db = db; 

In other files, you can require this:

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

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

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

I often do this, like other general settings and settings that I want to provide to routes:

 var initialize = function(app, config) { }; 

If you pass an instance of express app , you can set it as well:

 app.set('mongo', db); 

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

+15
source share

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

+3
source share

If you do not want to use express-mongo-db, you can do almost the same thing:

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. }); }); ... 
+1
source share

Get a database connection in a query using express-mongo-db package

In your App.js

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

In other files (routes etc) where you need to use the database

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

All Articles