Querying a collection with a bulk request using Mongoose Cursor

My current challenge involves working with rxJS and handling bulk HTTP requests from a database containing over 1 million documents.

The code I have is relatively simple. I am pushing all the documents from the collection into an array called "allPlayers" and then making bulk HTTP requests in batches of 20 to an API. While the code is functional, I believe it's time to refactor it from its current state:

        const cursor = players_db.find(query).lean().cursor();
        cursor.on('data', function(player) { allPlayers.push(player); });
        cursor.on('end', function() {
            logger.log('warng',`S,${allPlayers.length}`);
            from(allPlayers).pipe(
                mergeMap(player => getPlayer(player.name, player.realm),20),
            ).subscribe({
                next: player => console.log(`${player.name}@${player.realm}`),
                error: error => console.error(error),
                complete: () => console.timeEnd(`${updatePlayer.name}`),
            });
        });

Currently, I am using the 'find' method with 'cursor' and a 'batchSize', but based on my understanding from the length property, and the information from this related question on stack overflow: {mongoose cursor batchSize}, it seems like 'batchSize' is mainly for optimization and not for returning an array of X documents.

So, what should be my next steps and which operator in rxJS should I consider?

One approach could be to create arrays with the required length (e.g., 20) and then pass them to rxJS, similar to my previous usage. However, there might be another way to incorporate rxJS within the existing 'for promise loop'.

    const players = await players_db.find(query).lean().cursor({batchSize: 10});
    for (let player = await players.next(); player != null; player = await players.next()) {
        // implement RxJS functionality within this loop
    }

I also came across this question {Best way to query all documents from a mongodb collection in a reactive way w/out flooding RAM}, which addresses a similar issue. While I grasp the concept, I am unsure about the syntax. I'm aware that the 'cursor' variable doesn't directly provide useful data, or could it?

  1. The 'bufferCount' operator in rxJS seems intriguing.
  2. Could this solution {https://gist.github.com/wellcaffeinated/f908094998edf54dc5840c8c3ad734d3} be applicable?

Answer №1

After thorough investigation, it became clear that in this particular scenario, rxJS is not a necessity although it remains an option.

The resolution turned out to be surprisingly straightforward by simply utilizing MongoCursor:

async function BulkProcess (batchSize = 10) {
    try {
       let BulkProcessArray = [];
       const cursor = collection_db.find({}).lean().cursor({batchSize: batchSize});
       cursor.on('data', async (doc) => {
           BulkProcessArray.push(/*any function or axios instance*/)
            if (BulkProcessArray.length >= batchSize) {
                cursor.pause();
                console.time(`========================`);;
                await Promise.all(BulkProcessArray);
                BulkProcessArray.length = 0;
                cursor.resume();
                console.timeEnd(`========================`);
            }
       }
    } catch (error) {
       console.error(error)
    }
}

BulkProcess();

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

Error: Headers cannot be set once they have already been sent

My app.js file has the following code snippet: app.use(function(req, res, next){ if(!req.user){ return res.redirect('/login_'); } next(); }) Everything seems correct so far. In my route/index.js file, I have the following code: rout ...

Dynamic addition of modules to my Angular application is a must

Is there a way to dynamically load modules in my Angular application based on user selection after they have logged in? ...

Jackson Mixin: for deserializing route identifiers

I have implemented the Jackson Mixin for deserializing a mongo object and this is how my Mixin looks: public interface MyMixin { /** * Mixin to set key value for pojo. * @param key key * @param value value */ @JsonAnySetter void put(Stri ...

Utilizing a Custom Hook for Updating Components in useEffect

I am facing an issue with the following code snippet: function checklogin(callback) { if (!state.user.authenticated) pushhistory("/accounts/login", function(){teamhome2_message();}); else callback(); } // TRYING TO CONVERT IT INTO ...

Utilizing AJAX in Datatables- Effortlessly sharing a URL link to a designated page

I've recently encountered an issue while using Datatables and AJAX to retrieve data from my Rails server. The problem arises when I try to share a specific page (let's say page 2) with another user who is also using Datatables. Due to the paginat ...

Despite being installed, the message 'concurrently: command not found' pops up

I'm attempting to run two scripts simultaneously, and I came across the concurrently package that is supposed to assist with this. After executing npm install concurrently --save and verifying it in my package.json, I faced an issue when trying to run ...

What could be causing the post method to fail in this AngularJS example?

After successfully reading a JSON file in my sample code, I encountered an issue when trying to update the JSON file. The error message "Failed to load resource: the server responded with a status of 405 (Method Not Allowed)" appeared, even though the data ...

Accessing variables in subfunctions proves challenging for Node.js

Here is a function I've been working on to calculate the total price for a checkout process. However, when I console.log() the variable before it is returned, I get 0. But if I log the variable inside the findOne() function, I get the correct value. ...

Encountering difficulty obtaining return value from asynchronous function, await behaving inconsistently in Vue API Service

I am in the process of developing a new service to interact with my API. I am not very familiar with async/await, but I have encountered a puzzling issue that doesn't seem to align with what I've read in the documentation. When attempting to use ...

In what ways can we utilize a consistent state across various tabs or pages?

One feature of my application is a dynamic chart with various settings such as filters and time ranges. I want to save these settings in the app's state so they can be shared with other components on different pages. However, when switching tabs and r ...

How can we trigger the Skill bar effect upon scrolling to the section?

I have created a stunning Skill Bar that is functioning perfectly. However, I am looking to enhance the experience by having the skill bar effect trigger only when I scroll to that specific section. For example, as I navigate from the introduction section ...

Using AngularJS to dynamically swap out {{post.title}} with a different HTML file

I want to update the value of {{post.title}} within my HTML to redirect to another HTML file. <div ng-repeat="post in posts"> <h2> {{post.title}} <a ng-click="editPost(post._id)" class="pull-r ...

In JavaScript, the "this" keyword points to a different object

Here is a script that needs attention: Bla = function() { this.prop = 123; } Bla.prototype.yay = function() { console.log(this,this.prop); } X = new Bla(); $(document).ready(X.yay); // output: #document undefined --> why? $(document).ready(functio ...

The array is acting strangely and not functioning as expected

I am currently working with express, node, and mongoose. When I access my mongoDB database and log it to the console, I get the following array: module.exports ={ stories: function(req, res, next){ Story.find(function(err, stories){ if(err) ...

Incorporate external JavaScript libraries not built with Angular

Our project utilizes NPM in conjunction with Browserify for managing third-party dependencies, which pairs well with AngularJS due to the CommonJS-modules. Below is a code snippet showcasing the dependency structure that integrates seamlessly with Angular ...

The selected jquery script is failing to function as intended

I'm currently implementing jQuery chosen in a select element to enhance user experience, however I'm facing an issue when attempting to copy the chosen div to another div using jQuery $(document).ready(function() { $(".chosen").chosen({}); ...

Building a static website with the help of Express and making use of a public directory

It seems that I am facing a misunderstanding on how to solve this issue, and despite my efforts in finding an answer, the problem persists. In one of my static sites, the file structure is as follows: --node_modules --index.html --server.js --app.js The ...

Expanding VS 2013: Effective management of classes through item customization

Trying to accomplish a somewhat complex task, I have dedicated hours to searching for the appropriate documentation with no success. The goal is for Visual Studio to generate some JavaScript code and place it in a specific folder, starting from: Performi ...

Engaging 3D Object with JavaScript Interactivity

I'm currently working on a project for my HCI assignment where I need to create an interactive Sphere using JavaScript. However, I am new to JavaScript and Three.js. My goal is to have the sphere display statistics of a specific subject when clicked. ...

Using a JavaScript callback function as a parameter for the addJavascriptInterface method in Java

Can Java interact with arbitrary functional objects in JavaScript by calling them as callbacks? For example, if we have a function called 'access' that is registered to invoke a Java function: access(function(blabla){ ... }); Are there eff ...