4

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?

1 Answer 1

9

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

Sign up to request clarification or add additional context in comments.

1 Comment

:0 Thanks so much! "Spams the Accept Button" :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.