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) {
pawel
source share