假设我在Mongoose中运行这个查询:

    Room.find({}, (err,docs) => {
    
    }).sort({date:-1}); 

这行不通!


当前回答

正确答案是:

Blah.find({}).sort({date: -1}).execFind(function(err,docs){

});

其他回答

短期解决方案:

const query = {}
const projection = {}
const options = { sort: { id: 1 }, limit: 2, skip: 10 }

Room.find(query, projection, options).exec(function(err, docs) { ... });
Post.find().sort({date:-1}, function(err, posts){
});

应该也可以

编辑:

如果你得到sort()只接受1个参数的错误,你也可以尝试使用这个:

Post.find({}, {
    '_id': 0,    // select keys to return here
}, {sort: '-date'}, function(err, posts) {
    // use it here
});

今天使用Mongoose 3.5(.2)处理这个问题,没有一个答案能帮助我解决这个问题。下面的代码片段实现了这个目的

Post.find().sort('-posted').find(function (err, posts) {
    // user posts array
});

你可以发送find()所需的任何标准参数(例如where子句和return字段),但不能发送回调。如果没有回调,它将返回一个Query对象,您可以对其进行链式排序()。您需要再次调用find()(包含或不包含更多参数—出于效率原因不需要任何参数),这将允许您在回调中获得结果集。

我是这样做的:

Data.find( { $query: { user: req.user }, $orderby: { dateAdded: -1 } } function ( results ) {
    ...
})

这将首先显示最新的内容。

正确答案是:

Blah.find({}).sort({date: -1}).execFind(function(err,docs){

});