Skip to content

Instantly share code, notes, and snippets.

@viniciusCamargo
Last active April 15, 2017 20:52
Show Gist options
  • Save viniciusCamargo/ff541fdd3c779e46422f562ef9b249df to your computer and use it in GitHub Desktop.
Save viniciusCamargo/ff541fdd3c779e46422f562ef9b249df to your computer and use it in GitHub Desktop.
Simple promise wrapper around the MongoDB native driver for Node.js
const conn = require('./db')
let log = console.log.bind(this)
log.error = console.error.bind(this)
conn.then(db => {
db.collection('COLLECTION').find({}).toArray()
.then(data => log(data))
.catch(err => log.error(err))
db.close()
})
.catch(err => log.error(err))
const mongoClient = require('mongodb').MongoClient
let log = console.log.bind(this)
log.error = console.error.bind(this)
const databaseInfo = {
host: 'host',
port: 'port',
user: 'username',
pass: 'password',
db: 'database',
collection: 'collection',
get url () {
return `mongodb://${this.user}:${this.pass}@${this.host}:${this.port}/${this.db}`
}
}
const MONGO_URL = databaseInfo.url
const COLLECTION = databaseInfo.collection
const connection = (url) => {
return new Promise((resolve, reject) => {
try {
mongoClient.connect(url, (err, db) => {
if (err) {
reject(err)
}
resolve(db)
})
} catch (err) {
reject(err)
}
})
}
connection(MONGO_URL)
.then(db => {
db.collection(COLLECTION).find({}).toArray()
.then(data => log(data))
.catch(err => log.error(err))
db.close()
})
.catch(err => log.error(err))
// module.exports = connection(MONGO_URL)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment