【问题标题】:In Mongoose, how do I sort by date? (node.js)在猫鼬中,我如何按日期排序? (node.js)
【发布时间】:2011-08-15 02:16:00
【问题描述】:

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

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

这行不通!

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    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 });
    【解决方案2】:

    正确答案是:

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

    【讨论】:

    【解决方案3】:

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

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

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

    【讨论】:

      【解决方案4】:
      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){});
      【解决方案5】:

      我这样做:

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

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

      【讨论】:

      • $orderby 在 MongoDB 3.2 中已弃用,因此不应再使用。
      【解决方案6】:

      【讨论】:

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

      短解:

      const query = {}
      const projection = {}
      const options = { sort: { id: 1 }, limit: 2, skip: 10 }
      
      Room.find(query, projection, options).exec(function(err, docs) { ... });
      

      【讨论】:

        【解决方案8】:

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

        【讨论】:

          【解决方案9】:

          这个对我有用。

          `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});
           });`
          

          【讨论】:

            【解决方案10】:

            使用 Koa 的 ES6 解决方案。

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

            【讨论】:

              【解决方案11】:

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

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

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

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2013-01-22
                • 1970-01-01
                • 2019-09-16
                • 2021-01-14
                • 1970-01-01
                • 2020-11-17
                • 1970-01-01
                相关资源
                最近更新 更多