Is it possible to close a MongoDB connection using a different method other than the one mentioned in this function?

I am facing a challenge with uploading a substantial data set from my node.js application to a mongodb. The process involves running a for loop to fetch each result. Initially, I established the connection to the MongoDB within every iteration of the loop, but this approach led to crashes.

After moving the connection setup outside the loop, encountering issues with db.close(). Leaving it inside the loop results in prematurely closing the connection, causing the app to crash with the error:

MongoError: server instance pool was destroyed

However, when attempting to relocate the db.close() command outside the loop, it gets stuck and fails to exit the loop to proceed with subsequent operations.

I am seeking advice on how to efficiently close the database connection outside the for loop only upon completion of all iterations.

MongoClient.connect(url, function(err, db) {
    if (err) throw err;
    var dbo = db.db("mydatabase");
    //execute SQL query to fetch data

    for(result in sqldata) {

        myobj = {Number: sqldata[result].Num} //<--- this for loop produces 16000 entries

        dbo.collection("customers").insertOne(myobj, function(err, res) {
          if (err) throw err;
          console.log("1 document inserted");
          db.close(); //<--- this is the issue
    });
    }
  });

Answer №1

One way to handle the insert operations is by using the await keyword.

MongoClient.connect(url, async (err, db) => {
    if (err) throw err;
    var dbo = db.db("mydatabase");
    let results = [];
    //execute SQL query to fetch data

    for(result in sqldata) {
        myobj = {Number: sqldata[result].Num} //<--- this loop generates 16000 entries

        results.push(
            new Promise((resolve) => {
                dbo.collection("customers").insertOne(myobj, (err, res) => {
                    console.log(err ? 'Document not inserted' : 'Document inserted');
                    resolve();
                })
            })
        );
    }

    await Promise.all(results);

    db.close();
});

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

Is there a way to improve efficiency in JavaScript and JSON by reducing the size of the array?

My partner and I are currently collaborating on the development of a small web application. This app serves as an information hub, sourcing data from a JSON file that is expected to contain around 150 items, each with approximately 130 properties. As we c ...

Is there a way to divide my time during work hours using Javascript?

This is just a simple example. 9.00 - 18.00 I am looking to modify the schedule as follows: 9.00 - 10.00 10.00 - 11.00 11.00 - 12.00 12.00 - 13.00 13.00 - 14.00 14.00 - 15.00 15.00 - 16.00 16.00 - 17.00 17.00 - 18.00 The current code implementation see ...

OrbitControls in THREE.JS fail to function properly when a DOM Element is layered on top of the scene

I am attempting to position labels as elements with position:absolute; over a THREEJS scene. The issue arises when the mouse hovers over one of the labels (the red box in the example below), causing the events that trigger OrbitControls to be "halted" by t ...

Iterate through a collection of files in an asynchronous manner by leveraging promises and defer statements

I have a specific objective to navigate through a directory of files, perform certain operations on each file, and then produce a JSON object with a portion of the directory. Initially, I managed to achieve this using the synchronous functions in Node&apo ...

Warning: Unhandled promise rejection in Mongoose schema

Below is an example of my controller function: exports.pnumber = async(function* (req, res) { const user = new User() try { yield user.findOneAndUpdate(req.body.pnumber, req.body.uid) res.send('success') } catch (err) { console ...

Image Handpicked by JCrop User

Successfully implemented JCrop example code for selecting an area on an image with a preview and getting coordinates. However, the challenge lies in allowing users to select an image from their file system, display it in the browser, and perform the afore ...

Using jQuery and Ajax to efficiently handle the retrieval of large files while browsing

I have some large text files that are potentially multiple GB in size, and I am looking for a way to view them within a div element. The idea is to make an AJAX request for a more manageable chunk of the file, have the AJAX script (preferably in PHP) inte ...

Error: Invalid character encountered during login script JSON parsing

I found this script online and have been experimenting with it. However, I encountered the following error: SyntaxError: JSON.parse: unexpected character [Break On This Error] var res = JSON.parse(result); The problem lies in the file below as I am unf ...

Using ElectronJS requires the usage of the import keyword to load ES Modules

I've recently delved into Electron development by exploring the Electron Docs. I opted for ES6 syntax with import/export, while the documentation showcased the use of require. To align with ES Module standards, I updated my package.json file with typ ...

Creating a real-time face generator for a three.js shape

Currently, I am developing webgl software for generating 3D models that heavily relies on dynamic geometry. During my work, I have encountered some unusual behavior which I have managed to isolate in a JSFiddle demo. It appears that any new faces added af ...

The issue of multiple clicks being triggered when opening a dialog box: comparing the trigger and the click events

When I right-click on a jTree list item, a dialog box pops up for editing. The dialog box has a table with a list of items similar to the original one selected. The first time I open the dialog box, the selected item is highlighted and its information popu ...

Encountering Challenges when Implementing Next.js with Jest

When attempting to run a test in next.js using jest, an error keeps appearing: The issue may be due to the wrong test environment being used. Refer to https://jestjs.io/docs/configuration#testenvironment-string for more information. Consider utilizing the ...

Tips for adjusting the alignment of the Vuetify component "VDatePicker" based on the position of its parent component on the screen

Currently, I am utilizing the VMenu component from Vuetify which contains another Vuetify component called VDatePicker. The issue arises when clicking on a text field triggers the appearance of the calendar (VDatePicker). Normally, the VDatePicker componen ...

Vue Component Update DisorderI hope this meets your expectations

Below is my code using Bootstrap, Vue, and Axios: SETUP: *Please disregard the tab-contents in component_a main.js Vue.component('component_a', { props: ['info'], template: `<div> // Component A template code here } ...

Jquery form submission is failing, and a JavaScript warning appears in the console stating that 'body.scrollLeft is deprecated in strict mode' instead

In my JavaScript file, I've written the following code: function PS_SL_HandleEvent() { $(document).ready(function() { $('#form').removeAttr('onsubmit').submit(function(e) { if(acceptCGV()) { ...

Is it possible for me to create a variable that is assigned the width of the page as its value?

As I work on building a website for my company, I encountered an issue where certain divs overlap when the page is resized smaller. I am looking for a solution to dynamically adjust the CSS using JavaScript based on the width of the page. Despite attempti ...

React is still unable to display images when looping, despite the use of the "require"

I am facing an issue with extracting image paths from an array using the map function. The problem is that the image path is being printed as a string instead of rendering as an image. I tried using the require keyword, but I encountered an error stating " ...

Dealing with a Promise and converting it into an array: a step-by-step

I am encountering difficulties progressing with my Promise returned from the getPostedPlaces() function. After executing getAll(), an Array is displayed as shown below. Although the array appears to be correct, I am unsure how to make the getAll() function ...

recoil struggles to manage the error thrown by an asynchronous selector

Recoil offers the ability for users to throw errors in async selectors. For more information, please refer to the documentation. Both "<ErrorBoundary>" and "useRecoilValueLoadable()" can handle errors from async selectors, but I encountered issues w ...

The initial res.body object in NodeJS is enclosed in quotation marks

I've hit a roadblock while working on my social media website project using the MERN stack. Despite scouring the internet, I haven't been able to find a solution to the issue at hand. While following an online course, I encountered a problem tha ...