Skip to content

Instantly share code, notes, and snippets.

@bag-man
Last active July 22, 2019 22:46
Show Gist options
  • Save bag-man/43ff19786a11108b9dbf2d44ba98ffd8 to your computer and use it in GitHub Desktop.
Save bag-man/43ff19786a11108b9dbf2d44ba98ffd8 to your computer and use it in GitHub Desktop.
Connect and use MongoDB with ES6 in Node 4
'use strict'
const MongoClient = require('mongodb')
class Database {
constructor (uri) {
this.uri = uri
this.db = {}
return this
}
connect () {
return new Promise((resolve, reject) => {
MongoClient.connect(this.uri, (err, db) => {
if (err) reject(err)
this.db = db
resolve(this)
})
})
}
addReport (domain) {
return new Promise((resolve, reject) => {
this.db.collection('domains').findAndModify(
{ domain: domain }
, {}
, { $inc: { reported: 1 } }
, { new: true, upsert: true }
, (err, data) => {
if (err) reject(err)
resolve(data)
})
})
}
findReport (domain) {
return new Promise((resolve, reject) => {
this.db.collection('domains').findOne(
{ domain: domain }
, { _id: false, reported: true }
, (err, data) => {
if (err) reject(err)
if (data) {
resolve(data.reported)
} else {
resolve(0)
}
})
})
}
}
module.exports = Database
'use strict'
const Database = require('../database')
, dbUrl = process.env.MONGODB_URI || 'mongodb://localhost:27017/test'
, assert = require('assert')
describe('Database', () => {
let database
beforeEach((done) => {
database = new Database(dbUrl)
database.connect()
.then(() => { done() })
.catch((err) => { done(err) })
})
afterEach(() => {
database.db.dropDatabase()
})
it('should add a domain to the database with one report', (done) => {
database.addReport('google.com')
.then((data) => {
assert.equal(data.value.domain, 'google.com', 'domain not inserted')
return database.findReport('google.com')
})
.then((data) => {
assert.equal(data, 1, 'incorrect number of reports')
done()
})
.catch((err) => {
done(err)
})
})
})
@T-Rez-Owens
Copy link

This is great! Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment