Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB 'Server sockets closed' & no fix found

yesterday I started using the javascript MongoDB driver.

I've run into an issue, an error is persistently showing, however, data is still being stored.

Below you can see the javascript I use to initially connect to the DB, and then an insert query is initiated. When not initiating the insert query, the console outputs:

Connected correctly to server

Disconnected from server successfully

But when running with the insert query, an error is returned.

Connected correctly to server

{ [MongoError: server localhost:27017 sockets closed] name: 'MongoError',

message: 'server localhost:27017 sockets closed'}

Disconnected from server successfully

Could any one point me in the right direction?

MongoClient.connect(db_default.db_url, function(err, db) {
    console.log('Connected correctly to server');
    if(err) {
        console.log(err);
    }
    else {
         mongoInsert(db, 'user', user_default, function(user_res) { 
            console.log(user_res);
        });
    }
    db.close();
    console.log('Disconnected from server successfully');
});

function mongoInsert(db, collection_name, data,cb) {
    var collection = db.collection(collection_name);
    collection.insert(data, function(err, res) {
        if(err) {
            console.log(err);
        }
        else {
            console.log('Inserted into the ' + collection_name + ' collection');
            cb(res);
        }
    });
}
like image 435
Luke Bennett Avatar asked Oct 13 '14 18:10

Luke Bennett


1 Answers

Don't Close db connection before receiving results. Do as follow:

MongoClient.connect(db_default.db_url, function(err, db) {
    if(err) {
        console.log(err);
    }
    else {
         mongoInsert(db, 'user', user_default, function(user_res) { 
            console.log(user_res);
            db.close();
        });
    }

    console.log('Disconnected from server successfully');
});

function mongoInsert(db, collection_name, data,cb) {
    var collection = db.collection(collection_name);
    collection.insert(data, function(err, res) {
        if(err) {
            console.log(err);
        }
        else {
            console.log('Inserted into the ' + collection_name + ' collection');
            cb(res);
        }
    });
}
like image 149
Hamed Ghasemzadeh Avatar answered Oct 18 '22 17:10

Hamed Ghasemzadeh