Skip to content

Instantly share code, notes, and snippets.

@pbatey
Last active March 13, 2019 00:38
Show Gist options
  • Save pbatey/20d99ff772c29146897834d0f44d1c29 to your computer and use it in GitHub Desktop.
Save pbatey/20d99ff772c29146897834d0f44d1c29 to your computer and use it in GitHub Desktop.
An example of an express route that uses query-to-mongo
var express = require('express')
var mongoskin = require('mongoskin')
var ObjectID = require('mongodb').ObjectID
var query2m = require('query-to-mongo')
// attach db to the router
var db = mongoskin.db('mongodb://localhost:27017/mydb', {safe: true})
var router = express.Router()
router.db = db
router.use(function (req, res, next) {
req.db = router.db
next()
})
function normalizeId(id) {
if (ObjectID.isValid(id)) return new ObjectID(id)
return id;
}
router.param('id', function (req, res, next, id) {
req.idMatch = { _id: normalizeId(id) }
next()
})
// get an object from the collection
router.get('/mycollection/:id', function (req, res, next) {
var collection = req.db.collection('my')
collection.findOne(new ObjectId(req.idMatch), function (e, result) {
if (e) return next(e)
if (!result) res.status(404) // Not Found
res.locals.json = result
next()
})
})
// query objects in the collection
router.get('/mycollection', function (req, res, next) {
var query = query2m(req.query, { ignore: 'envelope' })
var collection = req.db.collection('my')
collection.count(query.criteria, function (e, count) {
var links
if (e) return next(e)
res.append('X-Total-Count', count)
var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl
links = query.links(fullUrl, count)
if (links) res.links(links)
collection.find(query.criteria, query.options).toArray(function (e, results) {
if (e) return next(e)
res.locals.json = results
next()
})
})
})
// attach the route to the app and serve
var app = express()
app.use('/api/v1', router)
var server = app.listen(3000, function () {
console.log('Listening on Port', server.address().port)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment