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

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

但这对我不起作用:

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

当前回答

还可以使用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) },
  ]);

其他回答

更新:

Post.find().sort({'updatedAt': -1}).all((posts) => {
  // do something with the array of posts
});

Try:

Post.find().sort([['updatedAt', 'descending']]).all((posts) => {
  // do something with the array of posts
});

从Mongoose 3.8.x开始:

model.find({ ... }).sort({ field : criteria}).exec(function(err, model){ ... });

地点:

条件包括asc、desc、升序、降序、1、-1

注意:使用引号或双引号

使用“asc”,“desc”,“ascending”,“descent”,1或-1

在Mongoose 4中使用查询生成器接口进行链接。

// Build up a query using chaining syntax. Since no callback is passed this will create an instance of Query.
var query = Person.
    find({ occupation: /host/ }).
    where('name.last').equals('Ghost'). // find each Person with a last name matching 'Ghost'
    where('age').gt(17).lt(66).
    where('likes').in(['vaporizing', 'talking']).
    limit(10).
    sort('-occupation'). // sort by occupation in decreasing order
    select('name occupation'); // selecting the `name` and `occupation` fields


// Excute the query at a later time.
query.exec(function (err, person) {
    if (err) return handleError(err);
    console.log('%s %s is a %s.', person.name.first, person.name.last, person.occupation) // Space Ghost is a talk show host
})

有关查询的更多信息,请参阅文档。

app.get('/getting',function(req,res){
    Blog.find({}).limit(4).skip(2).sort({age:-1}).then((resu)=>{
        res.send(resu);
        console.log(resu)
        // console.log(result)
    })
})

输出

[ { _id: 5c2eec3b8d6e5c20ed2f040e, name: 'e', age: 5, __v: 0 },
  { _id: 5c2eec0c8d6e5c20ed2f040d, name: 'd', age: 4, __v: 0 },
  { _id: 5c2eec048d6e5c20ed2f040c, name: 'c', age: 3, __v: 0 },
  { _id: 5c2eebf48d6e5c20ed2f040b, name: 'b', age: 2, __v: 0 } ]

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

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