How can you sort an array by its' inner array size with nodejs?












1















everyone. I'm very new to this backend thing, and i'm starting to figure out the basics.
I made a basic system of posts and comments on NodeJS and mongoose.
The thing is now i want to get the post with the most comments so in the homepage i can show the most popular ones.



I want to return the posts that have the largest array of comment ids.



I first tried doing this:



var mysort = { comments: 1 };

Post.find( {} )
.sort(mysort)
.exec( (err, posts)=>{
if(err) {
return res.status(400).json({
ok: false,
message: 'Error loading posts',

});
}

return res.status(200).json({
ok: true,
posts: posts
});
});


But it just returns the comments in an alphabetical order.



Thank you very much for your help and sorry for my bad english.










share|improve this question





























    1















    everyone. I'm very new to this backend thing, and i'm starting to figure out the basics.
    I made a basic system of posts and comments on NodeJS and mongoose.
    The thing is now i want to get the post with the most comments so in the homepage i can show the most popular ones.



    I want to return the posts that have the largest array of comment ids.



    I first tried doing this:



    var mysort = { comments: 1 };

    Post.find( {} )
    .sort(mysort)
    .exec( (err, posts)=>{
    if(err) {
    return res.status(400).json({
    ok: false,
    message: 'Error loading posts',

    });
    }

    return res.status(200).json({
    ok: true,
    posts: posts
    });
    });


    But it just returns the comments in an alphabetical order.



    Thank you very much for your help and sorry for my bad english.










    share|improve this question



























      1












      1








      1








      everyone. I'm very new to this backend thing, and i'm starting to figure out the basics.
      I made a basic system of posts and comments on NodeJS and mongoose.
      The thing is now i want to get the post with the most comments so in the homepage i can show the most popular ones.



      I want to return the posts that have the largest array of comment ids.



      I first tried doing this:



      var mysort = { comments: 1 };

      Post.find( {} )
      .sort(mysort)
      .exec( (err, posts)=>{
      if(err) {
      return res.status(400).json({
      ok: false,
      message: 'Error loading posts',

      });
      }

      return res.status(200).json({
      ok: true,
      posts: posts
      });
      });


      But it just returns the comments in an alphabetical order.



      Thank you very much for your help and sorry for my bad english.










      share|improve this question
















      everyone. I'm very new to this backend thing, and i'm starting to figure out the basics.
      I made a basic system of posts and comments on NodeJS and mongoose.
      The thing is now i want to get the post with the most comments so in the homepage i can show the most popular ones.



      I want to return the posts that have the largest array of comment ids.



      I first tried doing this:



      var mysort = { comments: 1 };

      Post.find( {} )
      .sort(mysort)
      .exec( (err, posts)=>{
      if(err) {
      return res.status(400).json({
      ok: false,
      message: 'Error loading posts',

      });
      }

      return res.status(200).json({
      ok: true,
      posts: posts
      });
      });


      But it just returns the comments in an alphabetical order.



      Thank you very much for your help and sorry for my bad english.







      javascript node.js mongodb mongoose






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 1 at 20:34









      Rinzler786

      71111




      71111










      asked Jan 1 at 19:23









      TagzTagz

      155




      155
























          1 Answer
          1






          active

          oldest

          votes


















          1














          You need Aggregation Framework and $size operator to create temporary field using $addFields and then you can use $sort to sort by that field (-1 means descending order)



          Post.aggregate([
          {
          $addFields: {
          commentsCount: { $size: "$comments" }
          }
          },
          {
          $sort: { commentsCount: -1 }
          }
          ]).exec( (err, posts)=>{
          if(err) {
          return res.status(400).json({
          ok: false,
          message: 'Error loading posts',

          });
          }

          return res.status(200).json({
          ok: true,
          posts: posts
          });
          });





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53998285%2fhow-can-you-sort-an-array-by-its-inner-array-size-with-nodejs%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            You need Aggregation Framework and $size operator to create temporary field using $addFields and then you can use $sort to sort by that field (-1 means descending order)



            Post.aggregate([
            {
            $addFields: {
            commentsCount: { $size: "$comments" }
            }
            },
            {
            $sort: { commentsCount: -1 }
            }
            ]).exec( (err, posts)=>{
            if(err) {
            return res.status(400).json({
            ok: false,
            message: 'Error loading posts',

            });
            }

            return res.status(200).json({
            ok: true,
            posts: posts
            });
            });





            share|improve this answer




























              1














              You need Aggregation Framework and $size operator to create temporary field using $addFields and then you can use $sort to sort by that field (-1 means descending order)



              Post.aggregate([
              {
              $addFields: {
              commentsCount: { $size: "$comments" }
              }
              },
              {
              $sort: { commentsCount: -1 }
              }
              ]).exec( (err, posts)=>{
              if(err) {
              return res.status(400).json({
              ok: false,
              message: 'Error loading posts',

              });
              }

              return res.status(200).json({
              ok: true,
              posts: posts
              });
              });





              share|improve this answer


























                1












                1








                1







                You need Aggregation Framework and $size operator to create temporary field using $addFields and then you can use $sort to sort by that field (-1 means descending order)



                Post.aggregate([
                {
                $addFields: {
                commentsCount: { $size: "$comments" }
                }
                },
                {
                $sort: { commentsCount: -1 }
                }
                ]).exec( (err, posts)=>{
                if(err) {
                return res.status(400).json({
                ok: false,
                message: 'Error loading posts',

                });
                }

                return res.status(200).json({
                ok: true,
                posts: posts
                });
                });





                share|improve this answer













                You need Aggregation Framework and $size operator to create temporary field using $addFields and then you can use $sort to sort by that field (-1 means descending order)



                Post.aggregate([
                {
                $addFields: {
                commentsCount: { $size: "$comments" }
                }
                },
                {
                $sort: { commentsCount: -1 }
                }
                ]).exec( (err, posts)=>{
                if(err) {
                return res.status(400).json({
                ok: false,
                message: 'Error loading posts',

                });
                }

                return res.status(200).json({
                ok: true,
                posts: posts
                });
                });






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jan 1 at 19:29









                micklmickl

                14.1k51637




                14.1k51637
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53998285%2fhow-can-you-sort-an-array-by-its-inner-array-size-with-nodejs%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Monofisismo

                    Angular Downloading a file using contenturl with Basic Authentication

                    Olmecas