Kil'jaeden
Kil'jaeden

Reputation: 969

connecting MongoDB in Node.js not working in for-loop

I have a function which connect my local mongoDB database, but the connection suddenly doesn't work when I try to put it in a for-loop.

var connectMongo = require("./ConnectToMongoDB");
var insertDocument = require("./InsertDocument");

function spamMongoDBtest(){
      process.nextTick(function(){
            var max = 500;
            for(var i = 0; i<max;i++){
                  setTimeout(function(){
                              connectMongo(insertDocument);
                        }, 50);
            }
      });
}

Why do I get this AssertionError:

AssertionError: null == { [MongoError: connect ECONNREFUSED] name: 'MongoError', message: 'connect ECONNREFUSED' }

connectMongo(insertDocument); DOES work in this function:

function spamMongoDB(){
      process.nextTick(function(){
      setInterval(function(){connectMongo(insertDocument); }, 100); });
}

Upvotes: 2

Views: 768

Answers (2)

Endre Simo
Endre Simo

Reputation: 11551

You are getting a connection error from MongoDb because you are trying to connect to database multiple times. You need to connect to database only once, and from that moment if the connection has been established the communication with database is opened.

You are opening the connection and once opened you can communicate with the database.

var mongoURI = "mongodb://localhost:3030/";
var MongoDB = mongoose.connect(mongoURI).connection;
MongoDB.on('error', function(err) { console.log(err.message); });
MongoDB.once('open', function() {
  console.log("mongodb connection open");
  insertDocument;
});

Inside the open function you can trigger the setInterval. Or if you want to stick with your code, each time you open a connection in the for loop you have to close it too. I don't know what connectMongo method contains, but after you invoke this method outside setTimeout method you have to close the connection. But this approach anyway will put on heavy duty the server, so my advice is to follow the method provided.

Upvotes: 1

Ita
Ita

Reputation: 911

Could you also share the connectMongo and insertDocument functions? Perhaps you have too many open connections to Mongo. Try closing the connection to Mongo after each time you write the document.

You can use the async library to limit the concurrency of your test.

For example:

var concurrency = 25; //limit to 25 concurrent connections
async.eachLimit(new Array(500), concurrency, function(item, callback) {
  connectMongo(function(){
    insertDocument();
    callback();
  });
});

Upvotes: 1

Related Questions