Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js MongoDB Sockets closed error

I'm currently making a login system for my NodeJS application. However, I get a strange error from MongoDB whenever I try retrieving a collection.

Error Message

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

Heres my code to connect to my db

    var username = req.body.user.username;
    var password = req.body.user.password;

    MongoClient.connect("mongodb://localhost:27017/myDb", function(err, db){
        assert.equal(null, err);

        var collection = db.collection("accounts");
        collection.findOne({"username": username}, function(err, item){
            console.log(item);
            console.log(err);
        });

        db.close();
    });

Is anyone able to see where Ive gone wrong?

like image 785
Jonty Morris Avatar asked Jan 06 '23 12:01

Jonty Morris


1 Answers

You are closing yourself the database before the find query is ever done (it is an async method). Remove that db.close() or move it on the findOne callback.

var username = req.body.user.username;
var password = req.body.user.password;

MongoClient.connect("mongodb://localhost:27017/myDb", function(err, db){
    assert.equal(null, err);

    var collection = db.collection("accounts");
    collection.findOne({"username": username}, function(err, item){
        console.log(item);
        console.log(err);
        db.close();
    });


});

By the way, you will have very poor performance by connecting/closing the DB connexion with each query and you should avoid doing that: connect once on the app startup and close the db on app close

like image 136
Jonathan Muller Avatar answered Jan 15 '23 00:01

Jonathan Muller