Skip to content

Instantly share code, notes, and snippets.

@chrisckchang
Last active April 16, 2018 19:33
Show Gist options
  • Save chrisckchang/6757209 to your computer and use it in GitHub Desktop.
Save chrisckchang/6757209 to your computer and use it in GitHub Desktop.
example express app that uses connection pooling (reuse db/coll object)
var express = require('express');
var mongodb = require('mongodb');
var app = express();
var MONGODB_URI = 'mongodb-uri';
var db;
var coll;
// Initialize connection once
mongodb.MongoClient.connect(MONGODB_URI, function(err, database) {
if(err) throw err;
db = database;
coll = db.collection('test');
app.listen(3000);
console.log('Listening on port 3000');
});
// Reuse database/collection object
app.get('/', function(req, res) {
coll.find({}, function(err, docs) {
docs.each(function(err, doc) {
if(doc) {
res.write(JSON.stringify(doc) + "\n");
}
else {
res.end();
}
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment