Skip to content

Instantly share code, notes, and snippets.

@jt2190
Last active December 20, 2015 15:39
Show Gist options
  • Save jt2190/6155303 to your computer and use it in GitHub Desktop.
Save jt2190/6155303 to your computer and use it in GitHub Desktop.
An express.js application that uses async.js to initialize a MongoDB database connection pool before the application starts listening for HTTP requests. The database connection pool is shared using an application-wide variable named 'mongodb'.
var async = require('async'),
MongoClient = require('mongodb').MongoClient,
express = require('express');
var MONGODB_URL = 'mongodb://<username>:<password>@<host>:<port>/<database>',
PORT = -1;
async.waterfall([
function(cb) {
MongoClient.connect(MONGODB_URL, function(err, db) {
if (err) {
return cb(err);
} else {
console.log("Connected to MongoDB");
cb(null, db);
}
});
},
function(db, cb) {
try {
app = express();
app.set('mongodb', db);
// Simple inline example of using the connection.
// You should use async or similar here as well
// (kriskowal/q is also popular) instead
// of nesting callbacks, and creating "callback hell".
app.get('/users/:userId', function(req, res, next) {
var db = req.app.get('mongodb'),
userId = req.params['userId'];
db.collection('users').findOne({'_id': userId}, function(err, userDoc) {
if (err) {
res.send(500);
}
if (!userDoc) {
res.send(404);
} else {
res.send(userDoc);
}
});
});
app.listen(PORT);
cb();
} catch (err) {
cb(err);
}
}
],
function(err, results) {
if (err) {
console.error(err.message);
} else {
console.log("App Started");
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment