Search code examples
javascriptnode.jssortingnode-mongodb-native

MongoDB sort with node-mongodb-native


I want to sort the result of a Mongo query. From here I found I could do it for example like this:

collection.find().sort( { name: 1 } ).limit( 5 )

As I dont want to sort by name, but by whatever is specified by request:

var query = require('url').parse(req.url, true).query;

var n = parseInt(query.limit);

var f = String(query.field);

var dir = query.direction;

collection.find().sort({f: dir}).limit(n)

Problem is, that it sortes by "f" and not whatever is value of variable f. How can I sort by whatever is stored in f ?


Solution

  • var query = require('url').parse(req.url, true).query;
    var n = parseInt(query.limit);
    var f = String(query.field);
    var dir = query.direction;
    var sortObj = {};
    sortObj[f] = dir;
    collection.find().sort(sortObj).limit(n)
    

    May be like this?