1.0.0 • Published 8 years ago

express-mongoose-sort v1.0.0

Weekly downloads
40
License
MIT
Repository
github
Last release
8 years ago

express-mongoose-sort

Parse req.query.sort to res.locals.sort

Installation

npm install --save express-mongoose-sort

Usage

Mount the middlewere in your router.

app.get('/api/items', require('express-mongoose-sort'), ctrl);

If there is a req.query.sort value, the middleware will convert it to something mongoose understands.

'?sort=-name,number'            => { name: -1, number: 1 }
'?sort[0]=-name&sort[1]=number' => { name: -1, number: 1 }
'?sort[name]=-1&sort[number]=1' => { name: -1, number: 1 }

NOTE: This module does not validate the actual sort properties. You might want to pick only the ones you know are valid for that specific route instead of passing directly to mongoose.

const _ = require('lodash');

function ctrl(req, res, next) {
  const sort = _.pick(res.locals.sort, ['name', 'number']);
  // ...
}

License

Copyright (c) 2016 Marius Craciunoiu. Licensed under the MIT license.