Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6901427
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T07:40:21+00:00 2026-05-27T07:40:21+00:00

Working with Nodejs and MongoDB through Node MongoDB native driver. Need to retrieve some

  • 0

Working with Nodejs and MongoDB through Node MongoDB native driver. Need to retrieve some documents, and make modification, then save them right back. This is an example:

db.open(function (err, db) {
  db.collection('foo', function (err, collection) {
    var cursor = collection.find({});
    cursor.each(function (err, doc) {
      if (doc != null) {
        doc.newkey = 'foo'; // Make some changes
        db.save(doc); // Update the document
      } else {
        db.close(); // Closing the connection
      }
    });
  });
});

With asynchronous nature, if the process of updating the document takes longer, then when cursor reaches the end of documents, database connection is closed. Not all updates are saved to the database.

If the db.close() is omitted, all the documents are correctly updated, but the application hangs, never exits.

I saw a post suggesting using a counter to track number of updates, when fall back to zero, then close the db. But am I doing anything wrong here? What is the best way to handle this kind of situation? Does db.close() have to be used to free up resource? Or does a new db connection needs to open?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T07:40:21+00:00Added an answer on May 27, 2026 at 7:40 am

    Here’s a potential solution based on the counting approach (I haven’t tested it and there’s no error trapping, but it should convey the idea).

    The basic strategy is: Acquire the count of how many records need to be updated, save each record asynchronously and a callback on success, which will decrement the count and close the DB if the count reaches 0 (when the last update finishes). By using {safe:true} we can ensure that each update is successful.

    The mongo server will use one thread per connection, so it’s good to either a) close unused connections, or b) pool/reuse them.

    db.open(function (err, db) {
      db.collection('foo', function (err, collection) {
        var cursor = collection.find({});
        cursor.count(function(err,count)){
          var savesPending = count;
    
          if(count == 0){
            db.close();
            return;
          }
    
          var saveFinished = function(){
            savesPending--;
            if(savesPending == 0){
              db.close();
            }
          }
    
          cursor.each(function (err, doc) {
            if (doc != null) {
              doc.newkey = 'foo'; // Make some changes
              db.save(doc, {safe:true}, saveFinished);
            }
          });
        })
      });
    });
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am working with Node.js to build a web socket server that uses mongodb.
What is the order of operations for the mongodb-native driver? Let's say you have
I have a working HTML file with some javascript in it. I use NodeJS
My node.js app uses express, socket.io and talks to mongodb through mongoose. All these
I'm working on a nodejs application. I managed to break some of the code
so ive been working on a small nodejs project and some of my user
Working on a project that parses a log of events, and then updates a
Working with python interactively, it's sometimes necessary to display a result which is some
I have just started working with nodejs. I wonder if there is a way
I'm working with EJS to render and server HTML pages from a Nodejs server.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.