假设我在Mongoose中运行这个查询:
Room.find({}, (err,docs) => {
}).sort({date:-1});
这行不通!
假设我在Mongoose中运行这个查询:
Room.find({}, (err,docs) => {
}).sort({date:-1});
这行不通!
当前回答
您也可以根据_id字段进行排序。例如,要获取最近的记录,你可以这样做,
const mostRecentRecord = await db.collection.findOne().sort({ _id: -1 });
它也快得多,因为我更愿意打赌,您的日期字段没有索引。
其他回答
ES6解决方案与Koa。
async recent() {
data = await ReadSchema.find({}, { sort: 'created_at' });
ctx.body = data;
}
今天使用Mongoose 3.5(.2)处理这个问题,没有一个答案能帮助我解决这个问题。下面的代码片段实现了这个目的
Post.find().sort('-posted').find(function (err, posts) {
// user posts array
});
你可以发送find()所需的任何标准参数(例如where子句和return字段),但不能发送回调。如果没有回调,它将返回一个Query对象,您可以对其进行链式排序()。您需要再次调用find()(包含或不包含更多参数—出于效率原因不需要任何参数),这将允许您在回调中获得结果集。
正确答案是:
Blah.find({}).sort({date: -1}).execFind(function(err,docs){
});
您也可以根据_id字段进行排序。例如,要获取最近的记录,你可以这样做,
const mostRecentRecord = await db.collection.findOne().sort({ _id: -1 });
它也快得多,因为我更愿意打赌,您的日期字段没有索引。
Mongoose中的排序在版本中不断发展,其中一些答案不再有效。从4.1开始。在Mongoose的x版本中,date字段的降序排序可以通过以下任何一种方式完成:
Room.find({}).sort('-date').exec((err, docs) => { ... });
Room.find({}).sort({date: -1}).exec((err, docs) => { ... });
Room.find({}).sort({date: 'desc'}).exec((err, docs) => { ... });
Room.find({}).sort({date: 'descending'}).exec((err, docs) => { ... });
Room.find({}).sort([['date', -1]]).exec((err, docs) => { ... });
Room.find({}, null, {sort: '-date'}, (err, docs) => { ... });
Room.find({}, null, {sort: {date: -1}}, (err, docs) => { ... });
对于升序排序,省略字符串版本上的-前缀或使用值1、asc或升序。