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

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

这行不通!


当前回答

这个适合我。

`Post.find().sort({postedon: -1}).find(function (err, sortedposts){
    if (err) 
        return res.status(500).send({ message: "No Posts." });
    res.status(200).send({sortedposts : sortedposts});
 });`

其他回答

短期解决方案:

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

Room.find(query, projection, options).exec(function(err, docs) { ... });

正确答案是:

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

});

看看这是否有助于>如何排序猫鼬?

也请阅读这个> http://www.mongodb.org/display/DOCS/Sorting+and+Natural+Order

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
});

您也可以根据_id字段进行排序。例如,要获取最近的记录,你可以这样做,

const mostRecentRecord = await db.collection.findOne().sort({ _id: -1 });

它也快得多,因为我更愿意打赌,您的日期字段没有索引。