Skip to content

Instantly share code, notes, and snippets.

@pablocattaneo
Last active January 8, 2019 11:54
Show Gist options
  • Save pablocattaneo/a98c54ab1d332bb16183bab95ffacb8b to your computer and use it in GitHub Desktop.
Save pablocattaneo/a98c54ab1d332bb16183bab95ffacb8b to your computer and use it in GitHub Desktop.
Utility setup
const mongodb = require('mongodb')
const MongoClient = mongodb.MongoClient
const mongoDbUrl = 'mongodb://localhost/database_name' // Standard URI connection scheme: mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
let _db
const initDb = callback => {
if (_db) {
console.log('Database is already initialized!')
return callback(null, _db)
}
MongoClient.connect(mongoDbUrl, {useNewUrlParser: true })
.then(client => {
_db = client
callback(null, _db)
console.log('Database connected!')
})
.catch(err => {
callback(err)
})
}
const getDb = () => {
if (!_db) {
throw Error('Database not initialzed')
}
return _db
}
module.exports = {
initDb,
getDb
}
const db = require('./db')
db.initDb((err, db) => {
if (err){
console.log(err)
} else {
app.listen(3000)
}
})1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment