我没有找到排序修饰符的doc。唯一的洞见在单元测试中: spec.lib.query.js # L12

writer.limit(5).sort(['test', 1]).group('name')

但这对我不起作用:

Post.find().sort(['updatedAt', 1]);

当前回答

// Ascending with updatedAt field
Post.find().sort('updatedAt').exec((err, post) => {...});

// Descending with updatedAt field
Post.find().sort('-updatedAt').exec((err, post) => {...});

参考网址:https://mongoosejs.com/docs/queries.html

其他回答

这就是我如何在mongoose.js 2.0.4中获得sort工作

var query = EmailModel.find({domain:"gmail.com"});
query.sort('priority', 1);
query.exec(function(error, docs){
  //...
});

更新

如果这让人困惑,还有更好的记录;在猫鼬手册中查看查找文档和查询如何工作。如果您想使用fluent api,您可以通过不提供find()方法的回调来获得查询对象,否则您可以指定如下所述的参数。

原始

给定一个模型对象,根据model文档,它是如何在2.4.1中工作的:

Post.find({search-spec}, [return field array], {options}, callback)

搜索规范需要一个对象,但您可以传递null或空对象。

第二个参数是一个字符串数组的字段列表,所以你可以提供['field','field2']或null。

第三个参数是作为对象的options,它包括对结果集进行排序的能力。您可以使用{sort: {field: direction}},其中field是字符串fieldname test(在您的情况下),direction是一个数字,其中1是升序,-1是降序。

最后一个参数(callback)是接收查询返回的docs集合的回调函数。

Model.find()实现(在这个版本中)执行滑动分配属性来处理可选参数(这让我感到困惑!):

Model.find = function find (conditions, fields, options, callback) {
  if ('function' == typeof conditions) {
    callback = conditions;
    conditions = {};
    fields = null;
    options = null;
  } else if ('function' == typeof fields) {
    callback = fields;
    fields = null;
    options = null;
  } else if ('function' == typeof options) {
    callback = options;
    options = null;
  }

  var query = new Query(conditions, options).select(fields).bind(this, 'find');

  if ('undefined' === typeof callback)
    return query;

  this._applyNamedScope(query);
  return query.find(callback);
};

HTH

Post.find().sort({updatedAt:1}).exec(function (err, posts){
...
});

解决方案:

posts.find().sort({field:1})  

//升序和降序使用-1而不是1

这是我如何得到排序工作在猫鼬2.3.0:)

// Find First 10 News Items
News.find({
    deal_id:deal._id // Search Filters
},
['type','date_added'], // Columns to Return
{
    skip:0, // Starting Row
    limit:10, // Ending Row
    sort:{
        date_added: -1 //Sort by Date Added DESC
    }
},
function(err,allNews){
    socket.emit('news-load', allNews); // Do something with the array of 10 objects
})