Skip to content

Instantly share code, notes, and snippets.

@viniciusCamargo
Last active March 6, 2017 16:56
Show Gist options
  • Save viniciusCamargo/0fd4181aa016288e87310a4db5f348b0 to your computer and use it in GitHub Desktop.
Save viniciusCamargo/0fd4181aa016288e87310a4db5f348b0 to your computer and use it in GitHub Desktop.
MongoDB middleware that exposes a DB object to Express.js req.param. https://github.com/floatdrop/express-mongo-db
const connection = require('mongodb').MongoClient.connect('mongoServer')
const mongoMiddleware = (req, res, next) => {
connection
.then(db => {
req['db'] = db.collection('documents')
next()
})
.catch(err => next(err))
}
app.use(mongoMiddleware)
app.get('/', (req, res) => {
req.db.find().toArray()
.then(docs => res.send(docs))
.catch(err => {
throw err
})
})
const ObjectID = require('mongodb').ObjectID
app.get('/:id', (req, res) => {
req.db.findOne({ _id: ObjectID(req.params.id) })
.then(doc => res.send(doc))
.catch(err => {
throw err
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment