【问题标题】:How to sort in mongoose?如何在猫鼬中排序?
【发布时间】:2011-05-17 01:06:02
【问题描述】:

我找不到排序修饰符的文档。唯一的见解是在单元测试中: spec.lib.query.js#L12

writer.limit(5).sort(['test', 1]).group('name')

但这对我不起作用:

Post.find().sort(['updatedAt', 1]);

【问题讨论】:

标签: javascript node.js mongodb mongoose


【解决方案1】:

你也可以使用 aggregate() 进行排序

 const sortBy = req.params.sort;
  const limitNum = req.params.limit;
  const posts = await Post.aggregate([
    { $unset: ['field-1', 'field-2', 'field-3', 'field-4'] },
    { $match: { field-1: value} },
    { $sort: { [sortBy]: -1 } },  //-------------------> sort the result
    { $limit: Number(limitNum) },
  ]);

【讨论】:

    【解决方案2】:

    您可以对查询结果进行排序

    Post.find().sort({createdAt: "descending"});

    【讨论】:

      【解决方案3】:

      从 Mongoose 3.8.x 开始:

      model.find({ ... }).sort({ field : criteria}).exec(function(err, model){ ... });
      

      地点:

      criteria 可以是 ascdescascendingdescending1-1

      注意:使用引号或双引号

      使用"asc""desc""ascending""descending"1-1

      【讨论】:

        【解决方案4】:

        在 Mongoose 中,可以通过以下任何一种方式进行排序:

            Post.find({}).sort('test').exec(function(err, docs) { ... });
            Post.find({}).sort([['date', -1]]).exec(function(err, docs) { ... });
            Post.find({}).sort({test: 1}).exec(function(err, docs) { ... });
            Post.find({}, null, {sort: {date: 1}}, function(err, docs) { ... });
        

        【讨论】:

        • 这几乎是Francisco Presencia链接的答案的直接副本。不幸的是,投票最高的答案已经过时并且不必要地冗长。
        • 这在今天还不太正确。 {sort: [['date', 1]]} 不起作用,但 .sort([['date', -1]]) 会起作用。看到这个答案:stackoverflow.com/a/15081087/404699
        • @steampowered 谢谢,我会进行编辑,如果我错了,非常欢迎您告诉我或编辑。
        • 希望看到一些关于结果的评论,尤其是。 1-1 值的含义是什么,而不是没有太多上下文的 4 行代码
        【解决方案5】:

        自 2020 年 10 月起,要解决您的问题,您应该将 .exec() 添加到调用中。不要忘记,如果你想在调用之外使用这些数据,你应该在异步函数中运行类似这样的东西。

        let post = await callQuery();
        
        async function callQuery() {
              return Post.find().sort(['updatedAt', 1].exec();
        }
        

        【讨论】:

          【解决方案6】:

          Mongoose v5.x.x

          升序排列

          Post.find({}).sort('field').exec(function(err, docs) { ... });
          Post.find({}).sort({ field: 'asc' }).exec(function(err, docs) { ... });
          Post.find({}).sort({ field: 'ascending' }).exec(function(err, docs) { ... });
          Post.find({}).sort({ field: 1 }).exec(function(err, docs) { ... });
          
          Post.find({}, null, {sort: { field : 'asc' }}), function(err, docs) { ... });
          Post.find({}, null, {sort: { field : 'ascending' }}), function(err, docs) { ... });
          Post.find({}, null, {sort: { field : 1 }}), function(err, docs) { ... });
          

          降序排列

          Post.find({}).sort('-field').exec(function(err, docs) { ... });
          Post.find({}).sort({ field: 'desc' }).exec(function(err, docs) { ... });
          Post.find({}).sort({ field: 'descending' }).exec(function(err, docs) { ... });
          Post.find({}).sort({ field: -1 }).exec(function(err, docs) { ... });
          
          
          Post.find({}, null, {sort: { field : 'desc' }}), function(err, docs) { ... });
          Post.find({}, null, {sort: { field : 'descending' }}), function(err, docs) { ... });
          Post.find({}, null, {sort: { field : -1 }}), function(err, docs) { ... });
          

          详情:https://mongoosejs.com/docs/api.html#query_Query-sort

          【讨论】:

          • 正如@Sunny Sultan 指出的那样,预示着所有Post.find({}, null, {sort: '-field'}, function(err, docs) { ... }); 用于下降,Post.find({}, null, {sort: 'field'}, function(err, docs) { ... }); 也用于上升工作。事实上,当我在 http 查询参数中传递字段和排序顺序时,将它们组合成一个字符串并使用这种方式对我的 bd 查询进行排序是我唯一的选择。
          【解决方案7】:
          Post.find().sort('updatedAt').exec((err, post) => {...});
          

          参考这里:https://mongoosejs.com/docs/queries.html

          【讨论】:

          • 您好,欢迎来到社区。虽然您的答案可能会提供解决方案,但一个好的答案需要一些解释。请添加一些参考资料和适当的解释。
          【解决方案8】:

          更新:

          Post.find().sort({'updatedAt': -1}).all((posts) => {
            // do something with the array of posts
          });
          

          试试:

          Post.find().sort([['updatedAt', 'descending']]).all((posts) => {
            // do something with the array of posts
          });
          

          【讨论】:

          • 在最新的 Mongoose (2.4.10) 中是.sort("updatedAt", -1)
          • 在更最新的 Mongoose(3.5.6-pre,但我很确定它适用于所有 3.x)中,它是 .sort({updatedAt: -1}).sort('-updatedAt')
          • 那么你应该使用exec(function (posts) {…而不是all
          • 我在 Mongoose 4.6.5 中有一个 all() must be used after where() when called with these arguments...
          • 我在 Node.js 中使用它,例如 javascript Post.find().sort({updatedAt: -1}).all((posts) => {
          【解决方案9】:

          从 4.x 开始,排序方法已更改。如果您使用 >4.x。尝试使用以下任何一种。

          Post.find({}).sort('-date').exec(function(err, docs) { ... });
          Post.find({}).sort({date: -1}).exec(function(err, docs) { ... });
          Post.find({}).sort({date: 'desc'}).exec(function(err, docs) { ... });
          Post.find({}).sort({date: 'descending'}).exec(function(err, docs) { ... });
          Post.find({}).sort([['date', -1]]).exec(function(err, docs) { ... });
          Post.find({}, null, {sort: '-date'}, function(err, docs) { ... });
          Post.find({}, null, {sort: {date: -1}}, function(err, docs) { ... });
          

          【讨论】:

            【解决方案10】:
            app.get('/getting',function(req,res){
                Blog.find({}).limit(4).skip(2).sort({age:-1}).then((resu)=>{
                    res.send(resu);
                    console.log(resu)
                    // console.log(result)
                })
            })
            

            输出

            [ { _id: 5c2eec3b8d6e5c20ed2f040e, name: 'e', age: 5, __v: 0 },
              { _id: 5c2eec0c8d6e5c20ed2f040d, name: 'd', age: 4, __v: 0 },
              { _id: 5c2eec048d6e5c20ed2f040c, name: 'c', age: 3, __v: 0 },
              { _id: 5c2eebf48d6e5c20ed2f040b, name: 'b', age: 2, __v: 0 } ]
            

            【讨论】:

              【解决方案11】:

              这是我做的,效果很好。

              User.find({name:'Thava'}, null, {sort: { name : 1 }})
              

              【讨论】:

                【解决方案12】:

                与 Mongoose 4 中的查询构建器界面链接。

                // Build up a query using chaining syntax. Since no callback is passed this will create an instance of Query.
                var query = Person.
                    find({ occupation: /host/ }).
                    where('name.last').equals('Ghost'). // find each Person with a last name matching 'Ghost'
                    where('age').gt(17).lt(66).
                    where('likes').in(['vaporizing', 'talking']).
                    limit(10).
                    sort('-occupation'). // sort by occupation in decreasing order
                    select('name occupation'); // selecting the `name` and `occupation` fields
                
                
                // Excute the query at a later time.
                query.exec(function (err, person) {
                    if (err) return handleError(err);
                    console.log('%s %s is a %s.', person.name.first, person.name.last, person.occupation) // Space Ghost is a talk show host
                })
                

                有关查询的更多信息,请参阅docs

                【讨论】:

                  【解决方案13】:
                  Post.find().sort({updatedAt:1}).exec(function (err, posts){
                  ...
                  });
                  

                  【讨论】:

                    【解决方案14】:
                    Post.find().sort({updatedAt: 1});
                    

                    【讨论】:

                      【解决方案15】:

                      这就是我设法排序和填充的方式:

                      Model.find()
                      .sort('date', -1)
                      .populate('authors')
                      .exec(function(err, docs) {
                          // code here
                      })
                      

                      【讨论】:

                        【解决方案16】:

                        更新

                        如果这让人们感到困惑,那么有一个更好的写法;查看猫鼬手册中的finding documentshow queries work。如果你想使用fluent api,你可以通过不提供find()方法的回调来获取查询对象,否则你可以指定参数,如下所述。

                        原创

                        给定一个model 对象,根据docs on Model,这就是2.4.1 的工作方式:

                        Post.find({search-spec}, [return field array], {options}, callback)
                        

                        search spec 需要一个对象,但您可以传递 null 或空对象。

                        第二个参数是作为字符串数组的字段列表,因此您可以提供['field','field2']null

                        第三个参数是作为对象的选项,其中包括对结果集进行排序的能力。您可以使用{ sort: { field: direction } },其中field 是字符串字段名test(在您的情况下),direction 是一个数字,其中1 是升序,-1 是降序。

                        最后一个参数 (callback) 是回调函数,它接收查询返回的文档集合。

                        Model.find() 实现(在此版本中)对属性进行滑动分配以处理可选参数(这让我很困惑!):

                        Model.find = function find (conditions, fields, options, callback) {
                          if ('function' == typeof conditions) {
                            callback = conditions;
                            conditions = {};
                            fields = null;
                            options = null;
                          } else if ('function' == typeof fields) {
                            callback = fields;
                            fields = null;
                            options = null;
                          } else if ('function' == typeof options) {
                            callback = options;
                            options = null;
                          }
                        
                          var query = new Query(conditions, options).select(fields).bind(this, 'find');
                        
                          if ('undefined' === typeof callback)
                            return query;
                        
                          this._applyNamedScope(query);
                          return query.find(callback);
                        };
                        

                        HTH

                        【讨论】:

                        • 对于投影:我们需要提供包含用空格分隔的列名的字符串。
                        【解决方案17】:

                        这就是我在 mongoose 2.3.0 中工作的方式:)

                        // Find First 10 News Items
                        News.find({
                            deal_id:deal._id // Search Filters
                        },
                        ['type','date_added'], // Columns to Return
                        {
                            skip:0, // Starting Row
                            limit:10, // Ending Row
                            sort:{
                                date_added: -1 //Sort by Date Added DESC
                            }
                        },
                        function(err,allNews){
                            socket.emit('news-load', allNews); // Do something with the array of 10 objects
                        })
                        

                        【讨论】:

                        • 在 mongoose 3 中,您不能再使用 Array 进行字段选择 - 它必须是 StringObject
                        • 顺便说一句,如果您想要所有字段,您可以在该部分中拉null(至少在 3.8 中)
                        【解决方案18】:

                        这就是我在 mongoose.js 2.0.4 中工作的方式

                        var query = EmailModel.find({domain:"gmail.com"});
                        query.sort('priority', 1);
                        query.exec(function(error, docs){
                          //...
                        });
                        

                        【讨论】:

                          【解决方案19】:

                          其他人为我工作,但这样做了:

                            Tag.find().sort('name', 1).run(onComplete);
                          

                          【讨论】:

                            【解决方案20】:

                            使用当前版本的 mongoose (1.6.0) 如果您只想按 一个 列排序,则必须删除数组并将对象直接传递给 sort() 函数:

                            Content.find().sort('created', 'descending').execFind( ... );
                            

                            花了我一些时间,才把事情做好:(

                            【讨论】:

                              猜你喜欢
                              • 2020-11-21
                              • 2019-09-16
                              • 1970-01-01
                              • 1970-01-01
                              • 1970-01-01
                              • 2011-08-15
                              • 1970-01-01
                              • 1970-01-01
                              相关资源
                              最近更新 更多