TIM*_*MEX 139 mongoose mongodb node.js
假设我在Mongoose中运行此查询:
Room.find({}, function(err,docs){
}).sort({date:-1});
Run Code Online (Sandbox Code Playgroud)
这不起作用!
Joh*_*yHK 384
Mongoose中的排序已经在发布版本中进行了演变,因此其中一些答案不再有效.从Mongoose 的4.1.x版本开始,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) { ... });
Run Code Online (Sandbox Code Playgroud)
对于升序排序,省略了-对字符串版本或使用值的前缀1,asc或ascending.
TIM*_*MEX 52
正确答案是:
Blah.find({}).sort({date: -1}).execFind(function(err,docs){
});
Run Code Online (Sandbox Code Playgroud)
小智 12
今天使用Mongoose 3.5(.2)处理这个问题并没有一个答案帮助我解决了这个问题.以下代码片段可以解决这个问题
Post.find().sort('-posted').find(function (err, posts) {
// user posts array
});
Run Code Online (Sandbox Code Playgroud)
您可以发送所需的任何标准参数find()(例如where子句和返回字段)但不回调.如果没有回调,它将返回一个链接的Query对象sort().您需要find()再次调用(有或没有更多参数 - 出于效率原因不需要任何参数),这将允许您在回调中获取结果集.
Post.find().sort({date:-1}, function(err, posts){
});
Run Code Online (Sandbox Code Playgroud)
也应该工作
编辑:
如果出现错误,您也可以尝试使用它sort() only takes 1 Argument:
Post.find({}, {
'_id': 0, // select keys to return here
}, {sort: '-date'}, function(err, posts) {
// use it here
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
144886 次 |
| 最近记录: |