Last active
January 8, 2019 11:54
-
-
Save pablocattaneo/a98c54ab1d332bb16183bab95ffacb8b to your computer and use it in GitHub Desktop.
Utility setup
This file contains hidden or 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 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 | |
} |
This file contains hidden or 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 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