Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

T-Rez-Owens commented Nov 10, 2017

This is great! Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.