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

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

但这对我不起作用:

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

当前回答

Post.find().sort({updatedAt: 1});

其他回答

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

这是我如何排序和填充的:

Model.find()
.sort('date', -1)
.populate('authors')
.exec(function(err, docs) {
    // code here
})

还可以使用aggregate()进行排序

 const sortBy = req.params.sort;
  const limitNum = req.params.limit;
  const posts = await Post.aggregate([
    { $unset: ['field-1', 'field-2', 'field-3', 'field-4'] },
    { $match: { field-1: value} },
    { $sort: { [sortBy]: -1 } },  //-------------------> sort the result
    { $limit: Number(limitNum) },
  ]);

在Mongoose中,排序可以通过以下任何一种方式完成:

    Post.find({}).sort('test').exec(function(err, docs) { ... });
    Post.find({}).sort([['date', -1]]).exec(function(err, docs) { ... });
    Post.find({}).sort({test: 1}).exec(function(err, docs) { ... });
    Post.find({}, null, {sort: {date: 1}}, function(err, docs) { ... });
Post.find().sort({updatedAt: 1});