Initiate a project and organize by using mongoose to sort array fields

My mongoose model for a post on a social networking platform is called PostModel:

{
caption: String,
likes: [] // array to store information about users who liked the video, essentially referencing another model
comments: [] // array to hold comment objects
}

I am trying to sort all the posts in a find query based on the number of likes, which is the length of the "likes" array. In case of posts with equal likes, I want to further sort them by the number of comments, i.e., the length of the "comments" array.

The sorting method I attempted seems to be not working as expected. Here is what I tried:

PostModel.find({}, {
  likes: { $size: "$likes" },
  comments: { $size: "$comments" }
}, 
{
  sort: { likes: -1, comments: -1 } // encountered error message "cannot sort with keys that are parallel arrays"
})

This issue made me suspect that the sorting operation occurs prior to projection. To verify this, I executed the following query:

PostModel.find({}, {
  _l: { $size: "$likes" },
  _c: { $size: "$comments" }
}, 
{
  sort: { _l: -1, _c: -1 }
})

Although this query did not produce any errors, it failed to sort the resulting array altogether. Hence, it confirmed my suspicion that projection takes place after sorting in mongoose.

In this scenario, how can I properly sort the array based on both the number of likes and comments?

Answer №1

After experimenting with this aggregation method, I found that it performs perfectly well with the provided data:

PostModel.aggregate([
  {
    '$set': {
      'likes': {
        '$size': '$likes'
      }, 
      'comments': {
        '$size': '$comments'
      }
    }
  }, {
    '$sort': {
      'likes': -1, 
      'comments': -1
    }
  }
])

I constructed this aggregation using Mongo Compass, a program that allows you to visually follow and build your aggregations step by step in real-time.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular list with a repeating group of radio buttons

I have a set of 'options', which consists of the following: {Id: 1, Label: "option 1"}, {Id: 2, Label: "option 2"} Additionally, I have a list of 'products' structured as follows: {Id: 1, Name: "Name 1", Recommend: options[0]}, {Id: ...

Go all the way down to see the latest messages

I have developed a messaging system using Vue. The latest messages are displayed from bottom to top. I want to automatically scroll to the end of a conversation when it is clicked and all the messages have been loaded via axios. Conversation Messages Comp ...

Angular 2 Integration for Slick Carousel

Greetings! I have recently ventured into Angular 2 and am currently attempting to get a carousel plugin called slick up and running. After some trial and error, I have successfully implemented it as a Component in the following manner: import { Component ...

What is the best way to describe the object within an array of items within a mongoose schema?

When creating an object inside of an array, should you just define the object directly within the array? How does MongoDB know to expect an array, and is querying on this array efficient? For example, let's take a look at this schema: const vancouve ...

Retrieve specific elements from an array based on the other elements present in the array

I am working with a result set that consists of various combinations from the following data structure: [ ["1st", "FELONY"], ["2nd", "FELONY"], ["3rd", "FELONY"], ["1st", "MISDEMEANOR"], ["2nd", "MISDEMEANOR"], ["3rd", "MISDEMEANOR"]] For example, it co ...

AngularJS $scope changes not reflecting in the view

Struggling with a persistent issue in my angularJS $scope. I've been working on updating an array within a controller function, and even though the values are changing based on console logs, the view isn't reflecting those changes. Here's wh ...

Utilizing AngularJS routes to load a specific URL when accessing a page for the first time

Working on developing a Single Page Application using AngularJS, my configuration settings appear as follows: app.config(["$routeProvider", function($routeProvider) { return $routeProvider .when("/", { redirectTo: " ...

Utilize JavaScript to apply the CSS -moz-transition

Creating a web application and using CSS3 to transform a div, but encountering a challenge with Firefox. Able to make Chrome, Opera, and IE work properly, except for Firefox. Here's how I'm setting up the working browsers: obj.style.WebkitTrans ...

When using Firestore in Android, I encounter a nodejs error regarding headers being sent prematurely

Currently, I am utilizing a webview in order to display content from a nodejs server. While requesting a page works as expected, accessing firestore results in an error where it seems like nodejs is attempting to resend the page. Below is the code for an a ...

Creating a Pre-authentication service for AWS Cognito using VueJS

Implementation of Pre-Authentication feature is needed in my VueJS application for the following tasks: Validation of ID/Refresh Token to check if it has expired. If the IdToken has expired, the ability to re-generate it using the Refresh Token or altern ...

Retrieve the text input from its respective radio button

There are two radio buttons, each accompanied by an input text field. When a user selects a radio button, they can also enter some corresponding text. My inquiry is: What is the best method to retrieve the entered text for the selected radio button? ...

Error displayed inline

I am facing an issue with a hidden textbox that I need to make visible based on a certain condition. Despite checking that the control is being triggered by the change event, I am unable to get it to display. I have experimented with different methods with ...

Transferring data between various stages of the user interface

As a newcomer to angularJs, I find myself facing an issue with two forms existing in different UI states (URLs) labeled as Step 1 and Step 2. The process requires filling up Step 1 and moving to the next step by clicking the NEXT button, which then leads t ...

Extract JSON data from Python API

Currently, I am delving into web programming and have created a Python API that queries an SQL database to return a JSON. The functionality of the API is as expected. In parallel, I've developed a controller where I execute a GET request to utilize t ...

Utilize AngularJS to refine and sort through data retrieved from an API

I have an Angular application that is fetching hotel data from an API. I want to filter the results based on the minimum price of the hotels being less than $50. $http.get($rootScope.baseurl + 'api/hotels/', { params: { page_ ...

What is the syntax for calling a constructor using "require"? Is it "require(module)(CONSTRUCTOR)"?

I am facing the following issue: I am trying to instantiate my constructor in this way: var object = require('module')([params]); The code for the module looks like this: function FunctionName(param) { // function body.. } exports = mod ...

obtainServerSideProps query parameter

Hey there, I'm trying to use NextJS and its getServerSideProps function to send an API Request, but I'm having trouble passing my ID Query Parameter along. The URL for my API is: http://localhost:3001/product/${id} Below is my code: const rout ...

Introducing HTML elements into pre-existing web pages

My interest lies in the idea of injecting HTML into existing web pages for enhanced functionality. Specifically, I am exploring the concept of creating a more efficient bookmarking system. As someone new to web development, I am unsure of how to achieve th ...

Sliding with jQuery to eliminate a div element

I wanted to dive into jQuery and decided to recreate the slick animation from Jay-Z's new album commercials. In these ads, a bar slides left over his name while simultaneously disappearing. I also wanted to add a flashing effect by fading out, fading ...

Using Javascript variables within Django HTML templates

As I develop my Django app, I find myself in uncharted territory with JavaScript. My goal is to integrate a map into one of my pages by adding a few lines of JavaScript. The JavaScript code includes initializing the map and placing markers based on data s ...