假设我在猫鼬中运行此查询:
Room.find({}, function(err,docs){
}).sort({date:-1});
这不起作用!
Sorting在Mongoose中随着版本的发展而演变,因此其中某些答案不再有效。从4.1.x Mongoose版本开始,可以通过以下任何一种方式对date
字段进行降序排序:
Room.find({}).sort('-date').exec(function(err, docs) { ... });
Room.find({}).sort({date: -1}).exec(function(err, docs) { ... });
Room.find({}).sort({date: 'desc'}).exec(function(err, docs) { ... });
Room.find({}).sort({date: 'descending'}).exec(function(err, docs) { ... });
Room.find({}).sort([['date', -1]]).exec(function(err, docs) { ... });
Room.find({}, null, {sort: '-date'}, function(err, docs) { ... });
Room.find({}, null, {sort: {date: -1}}, function(err, docs) { ... });
对于升序排序,请在字符串版本上省略-
前缀,或使用1
,asc
或ascending
的值。
正确的答案是:
Blah.find({}).sort({date: -1}).execFind(function(err,docs){
});
今天开始使用Mongoose 3.5(.2)处理此问题,没有一个答案能帮助我解决此问题。以下代码段可以解决问题
Post.find().sort('-posted').find(function (err, posts) {
// user posts array
});
您可以将所需的任何标准参数发送到find()
(例如where子句和返回字段),但要回调[[no。如果没有回调,它将返回一个查询对象,将其链接到sort()
。您需要再次调用find()
(带有或不带有更多参数-出于效率原因不需要任何参数),这将允许您在回调中获取结果集。
Data.find( { $query: { user: req.user }, $orderby: { dateAdded: -1 } } function ( results ) {
...
})
这将首先显示最新的信息。
Post.find().sort({date:-1}, function(err, posts){
});
也应该工作编辑:
如果出现错误sort() only takes 1 Argument
,也可以尝试使用此方法:
Post.find({}, { '_id': 0, // select keys to return here }, {sort: '-date'}, function(err, posts) { // use it here });
const query = {}
const projection = {}
const options = { sort: { id: 1 }, limit: 2, skip: 10 }
Room.find(query, projection, options).exec(function(err, docs) { ... });
_id
字段排序。例如,要获取最新记录,可以执行,const mostRecentRecord = await db.collection.findOne().sort({ _id: -1 });
它也要快得多,因为我更愿意打赌您的date
字段未编入索引。