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

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

这行不通!


当前回答

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

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

其他回答

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

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

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或升序。

正确答案是:

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

});

ES6解决方案与Koa。

  async recent() {
    data = await ReadSchema.find({}, { sort: 'created_at' });
    ctx.body = data;
  }

这里所有的答案实际上都是正确的,但是我写我的答案是为了说明,如果你在模型中没有一个名为“date”的字段,或者你在创建模型时在选项中传递了选项:timestamps: true,那么有时写“-date”或date: -1将不起作用。如果你正在使用timestamps: true,那么你需要输入:sort({createdAt: -1}),这样就可以工作了。