ChatGPT解决这个技术问题 Extra ChatGPT

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

假设我在 Mongoose 中运行此查询:

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

这不行!


M
Minsky

Mongoose 中的 Sorting 已经随着版本的发展而演变,因此其中一些答案不再有效。从 Mongoose 4.1.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) => { ... });

对于升序排序,省略字符串版本上的 - 前缀或使用 1ascascending 的值。


+1 展示了它可以完成的大量不同方式。但是,我在文档中找不到 Query#find 会接受这么多参数。签名是 Query#find([criteria], [callback])。我想也许有一些秘密握手说“标准”最多可以包含三个参数,但它将类型列为“对象”。
@Nateowami 您在文档中查看了错误的 find 方法。请参阅Model.find
你是对的。我看到他们使用的是 Module#property 符号并搜索了 #find。似乎没有简单的方法来导航或搜索文档。搜索 find 会产生 187 个结果。
您还可以按 _id 字段排序。例如,要获取最新记录,您可以执行以下操作:await db.collection.findOne().sort({ _id: -1 });
T
Timm

正确答案是:

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

});

上面示例的更新排序语法是:sort('-date') mongoosejs.com/docs/api.html#query_Query-sort
这个对我不起作用。我收到错误“User.find(...).sort(...).execFind 不是函数”
J
Jimmy Hillis

今天一直在使用 Mongoose 3.5(.2) 处理这个问题,但没有一个答案能帮助我解决这个问题。以下代码片段可以解决问题

Post.find().sort('-posted').find(function (err, posts) {
    // user posts array
});

您可以将所需的任何标准参数发送到 find()(例如 where 子句和返回字段),但 no 回调。如果没有回调,它会返回一个链接 sort() 的 Query 对象。您需要再次调用 find() (有或没有更多参数 - 出于效率原因不应该需要任何参数),这将允许您在回调中获得结果集。


m
mrid
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
});

这给了我错误:Error: sort() only takes 1 Argument
@LukeXF 请查看更新后的答案。我希望它可以帮助你:)
@mrid 它应该是这样的:Post.find({}, {'_id': 0}).sort("-date").function(err, posts){});
N
Noah

我这样做:

Data.find( { $query: { user: req.user }, $orderby: { dateAdded: -1 } } function ( results ) {
    ...
})

这将首先显示最新的内容。


$orderby 在 MongoDB 3.2 中已弃用,因此不应再使用它。
m
ms3300

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


C
Community

看看这是否有帮助 > How to sort in mongoose?

另请阅读此> http://www.mongodb.org/display/DOCS/Sorting+and+Natural+Order


第一种方法不起作用。它只是挂起......我认为这是因为 mongoose 的更新......而第二种方法只是我所知道的 mongo 文档。
find() 函数是 MongoDB 的函数,而不是 Mongoose。有关详细信息,请阅读 Mongoose API 页面 您可以将 MongoDB 文档中定义的语法与 Mongoose 一起使用。这就是为什么 Mongoose 没有自己的排序或相交查询。
d
davidsonsns

简短的解决方案:

const query = {}
const projection = {}
const options = { sort: { id: 1 }, limit: 2, skip: 10 }

Room.find(query, projection, options).exec(function(err, docs) { ... });

U
Usama Tahir

这个对我有用。

`Post.find().sort({postedon: -1}).find(function (err, sortedposts){
    if (err) 
        return res.status(500).send({ message: "No Posts." });
    res.status(200).send({sortedposts : sortedposts});
 });`

c
chovy

带有 Koa 的 ES6 解决方案。

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

M
Mike K

您还可以按 _id 字段排序。例如,要获取最近的记录,您可以这样做,

const mostRecentRecord = await db.collection.findOne().sort({ _id: -1 });

它也快得多,因为我非常愿意打赌您的 date 字段没有被索引。