0

When I run my server, after some queries, it throws the following error:

C:\Users\Me\Documents\Project\node_modules\mongodb\lib\mongo_client.js:415
          throw err
          ^
MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect EADDRINUSE 127.0.0.1:27017]
    at Pool.<anonymous> (C:\Users\Me\Documents\Project\node_modules\mongodb-core\lib\topologies\server.js:329:35)
    at emitOne (events.js:96:13)
    at Pool.emit (events.js:188:7)
    at Connection.<anonymous> (C:\Users\Me\Documents\Project\node_modules\mongodb-core\lib\connection\pool.js:280:12)
    at Connection.g (events.js:292:16)
    at emitTwo (events.js:106:13)
    at Connection.emit (events.js:191:7)
    at Socket.<anonymous> (C:\Users\Me\Documents\Project\node_modules\mongodb-core\lib\connection\connection.js:187:49)
    at Socket.g (events.js:292:16)
    at emitOne (events.js:96:13)

It is totally random but it mostly happens after 1000-2000 queries.

The node.js code to query is as follows:

let mongo = require('mongodb');
let MongoClient = mongo.MongoClient;
let url = "mongodb://localhost:27017/mydb";
function queryMongo(configurations, callback) {
    MongoClient.connect(url, (err, db) => {
        if (err) throw err;
        let query = {
            name: {
                $in: configurations
            }
        };
        db.collection("configurations").find(query).toArray((err, results) => {
            if (err) throw err;
            callback(results);
            db.close();
        });
    });
}

The queryMongo function is called as soon as the previous query is done. I tried deleting the lock files but it did not change anything. I copied the database to another computer but still the same problem.

dll
  • 161
  • 2
  • 21
  • At a quick stab, connecting and closing on a continual basis is not doing you any favours here. That alone is a big problem if your wider codebase repeats this pattern over and over. Instead you should be "persisting" the connection over the life-cycle of your application, which means until the app stops running itself. If you are continually creating connections, you have a strong chance of a leak, and at best Mongo is not releasing the connections right away and eventually hits a limit. – Neil Lunn Jul 21 '17 at 07:53
  • Oh thanks for the information. How should I achieve persistent connections? As I know mongodb does not have build in support for persistent connections. I tried by adding a global variable "var database;" and then doing "database = db" in order to be able to do "database.close()" somewhere else in my code but it does not work properly. – dll Jul 21 '17 at 08:09
  • try to monitor number of open connections with [mongostat](https://docs.mongodb.com/manual/reference/program/mongostat/), there are chances you hit the limit. Also check `db.serverStatus().connections`. – Alex Blex Jul 21 '17 at 08:17

0 Answers0