Mongo按动态字段排序

tim*_*g13 5 mongodb meteor

所以我传递了一个动态变量,这是我想要排序的字段的名称.

让我们说下面的sortVariable可能等于"price","createdAt","name"等.这不起作用,我怎么能这样做?

function findStuff (sortVariable) {
    var postings = Postings.find({
      "device.name": filter.exactDevice,
    }, {
      sort: {
        sortVariable: 1
      }
    });
    return postings;
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*don 11

您不能将变量用作对象文字中的键.尝试一下:

var findStuff = function(sortVariable) {
  var sort = {};
  sort[sortVariable] = 1;

  return Postings.find({
    'device.name': filter.exactDevice
  }, {
    sort: sort
  });
};
Run Code Online (Sandbox Code Playgroud)


Vis*_*tel 9

如果您使用的是 node v4,则可以使用 ES6 语法:

   find.sort({[sortVariable]: 1});
return Postings.find({
    'device.name': filter.exactDevice
  }, {
    sort: {[sortVariable]: 1}
  });
Run Code Online (Sandbox Code Playgroud)