Last active
July 5, 2017 13:50
-
-
Save WORMSS/d56a1d6d7c60814afffecb0bf190b911 to your computer and use it in GitHub Desktop.
Mongo Connection Sharing
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
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(); | |
}); |
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 _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; } | |
}; |
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
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