Last active
March 6, 2017 16:56
-
-
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
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 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