Last active
April 16, 2018 19:33
-
-
Save chrisckchang/6757209 to your computer and use it in GitHub Desktop.
example express app that uses connection pooling (reuse db/coll object)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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