Looping over Axios GET requests triggers an error stating "Sort exceeded memory limit"

Attempting to retrieve entries from my mongoDB database one by one, I encountered an issue after successfully loading around 400 out of 1000 entries. The error message reported was:

Executor error during find command :: caused by :: Sort exceeded memory limit of 33554432 bytes, but did not opt in to external sorting. Aborting operation. Pass allowDiskUse:true to opt in.

The Axios get request structure is as follows:

    for (let i = 0; i < total; i++) {
      await axios({
        method: "GET",
        url: "/api/entries/",
        params: { from: index + i, _limit: 1 },

      })
        .then((res) => {
          setPics((prev) => {
            return [...new Set([...prev, ...res.data])];
          });
          setIndex((prev) => prev++)
          setMoreEntries(res.data.length > 0)
        })

    }

In the controller, the GET function implementation is as shown below:

const getEntries = asyncHandler(async (req, res) => {
  const entries = await Entry.find().allowDiskUse(true).sort({ createdAt: 'desc' }).skip(req.query.from).limit(req.query._limit)
  res.status(200).json(entries)
})

Everything functions flawlessly until about halfway through the loading process when it encounters a breaking point. Although I attempted using allowDiskUse(true) to address the issue, the same outcome persisted.

Note: Removing the .sort({ createdAt: 'desc' }) resolves the problem, however, the order of entries loaded becomes inverted.

Answer №1

The structure appears to be correct, and it is puzzling why it isn't functioning as expected for you.

I have a couple of hypotheses that may explain the issue:

  1. It's possible that your database is hosted on Atlas, and you are utilizing unqualified instances for these operations, as outlined in their documentation:

Atlas M0 free clusters and M2/M5 shared clusters do not support the allowDiskUse parameter.

  1. Another potential explanation could be related to mongoose. It could be that you are using an outdated version with incompatible syntax or issues regarding the cursor flag.

Irrespective of the root cause, I suggest addressing this by either:

  1. Creating an index on createdAt. When sorting with an existing index, document scanning into memory is avoided, enhancing query efficiency and resolving the problem.

  2. Utilize the _id index for sorting with { _id: -1}. Given your mention of eliminating the sort operation and receiving documents in reverse order, it seems logical to use the ObjectId _id, which increases monotonically for sorting purposes.

Answer №2

I decided to tackle the problem by implementing a reverse for-loop and utilizing skip instead of sort, as shown below:

const fetchItem = asyncHandler(async (req, res) => {
  const data = await Data.findOne({}, {}).allowDiskUse(true).skip(req.query.offset)
  
  res.status(200).json(data)
})

This approach worked perfectly in my case, although I appreciate Tom's response which provided the solution I was seeking. Thank you!

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

Tweet button script fails to work properly when inserted via ajax loading

The following code snippet is used for Twitter integration: <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="https://platform.twitter.com/widgets.js";fjs.parentNode.in ...

Creating a secure authentication system with Parse for password recovery and website logins

Our organization has chosen to utilize a Parse backend for managing user accounts, and I am tasked with creating web pages for functionalities like password reset that will seamlessly integrate with our mobile applications. It has been some time since I ha ...

How can I implement Jquery validation engine ajax for two different fields using the same function?

The jQuery validation engine plugin has a unique feature of performing ajax validation. However, there is a minor inconvenience with this functionality. Instead of validating the field name, it sends the field ID for validation. Why does this pose a prob ...

What is the best method for sending a JSON array to the server from the client side?

Utilizing jQuery, I have created a JSON array and now I am looking to send this data from the client side to the server/backend through a modal window. Upon clicking "Save Changes" on the modal window, my goal is to transmit the var data = $(this).serial ...

Issues arising from JavaScript/jQuery dysfunction

I've successfully implemented this code in jsfiddle, but I'm struggling to make it work on my local files like index.html, index.css, index.js. Can someone please guide me on how to achieve this locally and not just on jsfiddle? Here's the j ...

Merging Documents in PouchDB

I need to retrieve equipment data from pouchdb/couchbase that has users assigned to them. Each piece of equipment has an _id and a checkedOutBy field with the user._id as its value. The employee object contains the user's name. How can I retrieve the ...

The search functionality is malfunctioning within the JavaScript table

I am working with a table that I want to filter based on input values. However, the current filtering function is not working as expected. I have utilized an onkeyup function for the filtering process. For more details and a live example, check out the jsf ...

Is there a way to decrease the jQuery UI file size?

Hey everyone! I recently downloaded a search box suggestion from this link. However, I noticed that the .js file at is quite large at 426kb. Does anyone know of a way to reduce the code within the file or have any simpler coding suggestions for creating ...

The error message "Unable to access the property 'map' of an undefined component" is displayed when trying to call

Introducing my newest component, userRow: Let's take a closer look at userRow: export default function UserRow(props, {data}) { const style = styles(); const userList = data.map((row) => { return { name: row, details: row }; ...

A comprehensive guide on integrating jQuery with jsdom using TypeScript

I am struggling to use jQuery with jsdom in typescript. This is the snippet of code I currently have: import { JSDOM } from 'jsdom'; import jQueryFactory from 'jquery'; const jsdom = new JSDOM(html); const { window } = jsdom ...

The Recharts Line chart fails to display newly added data points when data is updated

My app features a straightforward tool that enables users to monitor their weight changes over time. Despite successfully receiving new data in the props, the chart does not update and display the new point. Recharts Component: import React from 'rea ...

The font in my Next.js / Tailwind CSS project starts off bold, but unexpectedly switches back to its original style

I recently integrated the Raleway font into my minimalist Next.js application with Tailwind CSS. I downloaded the font family in .ttf format and converted it to .woff2, but I'm having trouble changing the font weight using custom classes like font-bol ...

Utilizing information shared between parent and child classes to plot points on a globe

Working on an exciting project to enhance my ReactJS and ThreeJS knowledge, I encountered an issue with passing data from the parent class to functions in the child class. Here's a glimpse of my project: App.js import React, {Component} from 'rea ...

localization within vue component

if (self.form.pickupTime == '') { self.formError.pickupTime = 'Please enter a pickup time that is ready for collection.'; status = false; return status; } else { self.formError.pickupTime = ''; } I am struggling ...

How can I place a THREE.ArrowHelper on a specific layer in Three.js?

Exploring the world of Three.js, I'm striving to understand how to organize elements onto separate layers. One of the challenges I'm facing involves an ArrowHelper that I've set up and added to the scene in the following manner: var ar ...

Troubles encountered with switching npm registry

In my Vue 2.7 project with vuetify, I initially installed dependencies using a custom local npm registry, acting as a proxy to the default npm. As the project has expanded, I've started using git actions to deploy to a development server, with varying ...

Struggling to retrieve information from a JSON file and display it within a component?

After accessing the JSON data and storing the necessary values in a dictionary named details, I am encountering an issue where the values are displayed when console logged from inside the function but appear as undefined when console logged in the parent f ...

The CSS class is not properly implemented in the React component

I value your time and assistance. I have spent many hours trying to solve this issue but seem unable to reach a resolution. Here is the React component in question: import styles from './style.scss'; class ButtonComponent extends React.Compone ...

Encountering a build error when using the @babel parser on Netlify with npm

Lately, I've been facing numerous challenges with the babel parser, particularly related to config files. Presently, I'm encountering an error on Netlify: 3:56:37 AM: Installing npm packages using npm version 8.19.4 3:56:41 AM: npm ERR! code E404 ...

A guide on simulating HTTP methods in Jest when dealing with private methods

I'm grappling with how to simulate the following functionality. I need to simulate both methods: getAllBookInCategory, deleteBookInCategory The public method invokes private methods and I presume I don't need to test private methods, only callin ...