Can mongoose-paginate-v2 be used to easily navigate through populated documents?

My User and Post models are set up, with User.favPosts being an array of references to the Post model. When I call paginate like this:

options = { populate: {path: 'favPosts'} };
const result = await User.paginate({}, options)

The resulting user document is now populated with posts:

{
  "docs": [
    {
      "_id": "6299ffa5c2ca4cdeebd1f513",
      "name": "user",
      "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4b2e262a22270b262a222765282426">[email protected]</a>",
      "favPosts": [
        {
          "_id": "629b299897f46f31761ad7a7",
          "title": "Available Test 5",
          "description": "Lorem ipsum dolor sit"
        },
        {
          "_id": "629b1edf108e765744d2560d",
          "title": "Available Test 4",
          "description": "Lorem ipsum dolor sit"
        },
        {
          "_id": "629b1c0027bf0eb197c057dd",
          "title": "Available Test 4",
          "description": "Lorem ipsum dolor sit"
        }
      ]
    }
  ],
  "totalDocs": 1,
  "offset": 0,
  "limit": 10,
  "totalPages": 1,
  "page": 1,
  "pagingCounter": 1,
  "hasPrevPage": false,
  "hasNextPage": false,
  "prevPage": null,
  "nextPage": null
}

I am currently able to paginate users, but I want to be able to paginate the populated documents (posts) as well, including getting the total count, page numbering, etc. The desired result should look like this:

{
  "docs": [
    {
      "_id": "629b299897f46f31761ad7a7",
      "title": "Available Test 5",
      "description": "Lorem ipsum dolor sit"
    },
    {
      "_id": "629b1edf108e765744d2560d",
      "title": "Available Test 4",
      "description": "Lorem ipsum dolor sit"
    },
    {
      "_id": "629b1c0027bf0eb197c057dd",
      "title": "Available Test 4",
      "description": "Lorem ipsum dolor sit"
    }
  ],
  "totalDocs": 3,
  "offset": 0,
  "limit": 10,
  "totalPages": 1,
  "page": 1,
  "pagingCounter": 1,
  "hasPrevPage": false,
  "hasNextPage": false,
  "prevPage": null,
  "nextPage": null
}

Is it possible to achieve this using mongoose-paginate-v2?

Answer №1

After some exploration, I discovered a different approach to the problem. Instead of utilizing mongoose-paginate-v2, I turned to the mongoose-aggregate-paginate-v2 module:

const aggregate = User.aggregate([ // This is a Promise without using "await"
    { $match: { userId } }, // Filtering for users in the collection
    {
// Adding posts:
        $lookup: {
            from: 'posts',
            localField: 'favPosts',
            foreignField: '_id',
            as: 'documents',
            pipeline, // Applying post filters here
        },
    },
// Using unwind + replaceRoot to move posts to the root level, creating an array of posts instead of users
    {
        $unwind: '$documents',
    },
    {
        $replaceRoot: { newRoot: '$documents' },
    },
]);

Next step was passing this Promise to the paginator:

const options = { page: 2, limit: 10 };
const result = await User.aggregatePaginate(aggregate, options);

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

Circle a component around another on the vertical axis (z-index)

A plugin caught my eye some time back, but I'm having trouble locating it. This nifty tool operates by positioning an element behind another one, then smoothly sliding it to the right. After that, it changes the z-index so the element appears larger i ...

When hovering over the background, it will enlarge but the text in front will remain the same size

As the user hovers over the image, the image enlarges. However, there is also some information that needs to be displayed in front of the image. This is my current implementation: .home-about-link { overflow: hidden; width: 100%; } .home-about { ...

Creating a dynamic user interface in Angular 6 that successfully tracks changes without reliance on the parent

As I delve into the world of Angular, I am faced with a challenge in creating a reusable component that will be bundled into an npm module. The issue lies in the UI change detection aspect. In order for the component to function properly, the application ...

Fresh ajax requests are not clearing the current data displayed in the JSP table

My ajax function retrieves data from a servlet and displays it in the page successfully. However, each time a new ajax call is made, the form appends the new data to the existing results instead of replacing them. I need to reset the current values stored ...

Extract information from a JSON Object using a specific pathway

Let's consider a scenario where we have a JSON Object structured as follows: var data = { "name": "abcd", "age": 21, "address": { "streetAddress": "88 8nd Street", "city": "New York" }, "phoneNumber": [ { ...

Showing XML content with JavaScript

Trying to parse a simple XML list using JavaScript, but having trouble formatting it the way I need. <TOURS> <MONTH> <TOUR> <NUMBER>1</NUMBER> <VENUE>City Name - Venue Name</VENUE> < ...

What are the methods for altering the material of a glTF model using THREE.js?

I've created a model using Blender and baked all the lighting and textures. However, when I import it into THREE.js in .glb format, it automatically uses the standard material. While this may work in certain cases, my concern is that I want to retain ...

The art of breaking down a content list into pages using JavaScript or jQuery

I am looking to modify my webpage which currently displays 100 videos all at once on a single page. Is there a way to only show 20 of the videos initially and cycle through the rest using Next and Previous buttons with the help of jQuery or JavaScript? ...

Is it necessary for me to retrieve any crucial information from the switch cases, or is simply having them set up in this way sufficient to distinguish between various PHP

I'm currently in the process of setting up an admin page with multiple panels. The idea is that clicking on the various images will dynamically change the content of the replaceThis div to display the corresponding PHP file. <div class="left-c ...

The error remains a mystery to the console - could it be possibly linked to the onclick() method?

Despite checking thoroughly, the console remains empty. I came across this code in a video tutorial where it worked perfectly. Below is the simple code that I am currently using: function addItem() { inames = [] iqtyp = [] iprice = [] inames.pu ...

Trapped in the Web of Facebook OAuth

I've been struggling with this issue for a day now and I can't seem to pinpoint where I'm going wrong. I have experience working with JavaScript on the client side and recently started following a book tutorial. However, it appears that Face ...

Encountering an issue with importing createSagaMiddleware from 'redux-saga' while working on my create-react-app project

Within my create-react-app, I have the following import: import createSagaMiddleware from 'redux-saga'; However, there seems to be an issue with importing createSagaMiddleware in my system. The versions I am currently using are: node 12.13.0 n ...

Navigating Through Grid and Card Content in React

My goal was to minimize the amount of code by incorporating a reusable component into my application. I am facing an issue on how to iterate through the columns and rows in Grid, Card, and Table. What would be the optimal solution for this problem? Please ...

Building complex queries with the MongoDB C# driver using the native API

When working with Linq in C#, you are able to write code similar to the following: public static class MyEntityExtensions { public static IQueryable<MyEntity> ByCodeSystem(IQueryable<MyEntity> items, int codeSystemId) { return item ...

Trigger the input with a delay function, pause if the input value is modified

I am in the process of creating an angular directive that will run a function when the input value changes. I want to implement a 300ms delay before running this function, but if the value changes again within the 300ms timeframe, I need to reset the delay ...

What steps should I take to include a Follow - Unfollow Button on my Website?

I need to add a button on my website that allows users to either follow or unfollow a specific game. Here is the table for the follow buttons: Follow Button Table When a user clicks on the button related to the game ID, it should update the game_follow d ...

Karma jasmine and an angular controller that utilizes the 'Controller as' syntax (where 'this' is used instead of $scope)

I'm having trouble setting up karma for my unit tests, specifically on a basic example: Here is the controller file: angular.module('balrogApp.requests', [ /* Dependencies */ ]) // Routes configuration .config(['$routeProvider&a ...

What are some methods for creating a Venn Diagram that includes data within each section using SVG, CSS, or Canvas?

I am attempting to replicate this visual representation using pure SVG, CSS, or Canvas drawing. So far, I have successfully created three circles that overlap and placed a label in the center of each one. However, I'm facing challenges when it comes t ...

Trouble with Javascript file functioning correctly

I am currently working on a mini game project using HTML, CSS, and JavaScript. Everything seems to be running smoothly with the HTML, CSS, and most of the JavaScript code. However, when I test the program in FireFox and attempt to click on a square div th ...

If a checkbox is checked, then the value in the textbox should be multiplied by 0

I'm faced with a challenge involving a non-clickable textbox that is meant to hold a running total. Each time a checkbox is clicked, its value should be added to the total in the textbox. However, I am now struggling to figure out how to perform mult ...