Skip to content

Instantly share code, notes, and snippets.

@WORMSS
Last active July 5, 2017 13:50
Show Gist options
  • Save WORMSS/d56a1d6d7c60814afffecb0bf190b911 to your computer and use it in GitHub Desktop.
Save WORMSS/d56a1d6d7c60814afffecb0bf190b911 to your computer and use it in GitHub Desktop.
Mongo Connection Sharing
Promise.resolve()
.then(() => require("./lib/mongoUtil").connect()) // Here you could pass in { host: "something", port: "something", dbname: "something" } to connect
.then(() => require("./lib/server"))
.catch(err => {
console.error("Error:", err);
process.exit();
});
var _db;
module.exports = {
connect: function ({host = "localhost", port = 27017, dbname = "exampleDb"} = {}) {
return require("mongodb").MongoClient.connect(`mongodb://${host}:${port}/${dbname}`)
.then(db => _db = db);
},
collection: function (col_name) {
if ( !_db ) {
return null;
}
return _db.collection(col_name);
},
get db() { return _db; }
};
const Video = require("../lib/mongoUtil").collection("Video");
/* or for multiple */
const db = require("../lib/mongoUtil").db;
const Video = db.collection("Video");
const User = db.collection("User");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment