在Mongoose中,我如何按日期排序?(的node.js)

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,ascascending.

  • +1 用于展示大量不同的方法。但是,我在文档中找不到 [Query#find](http://mongoosejs.com/docs/api.html#query_Query-find) 将采用那么多参数。签名是`Query#find([criteria], [callback])`。我想也许有一些秘密握手说“标准”最多可以包含三个参数,但它将类型列为“对象”。 (3认同)
  • 您还可以按“_id”字段排序。例如,要获取最新的记录,您可以执行以下操作:`await db.collection.findOne().sort({ _id: -1 });` (3认同)

TIM*_*MEX 52

正确答案是:

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

});
Run Code Online (Sandbox Code Playgroud)

  • 上面示例的更新排序语法是:sort(' - date')http://mongoosejs.com/docs/api.html#query_Query-sort (13认同)
  • 这个对我不起作用.我收到一个错误"User.find(...).sort(...).execFind不是一个函数" (3认同)

小智 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()再次调用(有或没有更多参数 - 出于效率原因不需要任何参数),这将允许您在回调中获取结果集.


lyn*_*vbg 7

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)