最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Node.js MongoDB Sockets closed error - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question edited May 31, 2018 at 9:47 Donald Duck is with Ukraine 8,91223 gold badges79 silver badges102 bronze badges asked Mar 5, 2016 at 10:01 Jonty MorrisJonty Morris 8072 gold badges12 silver badges26 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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

发布评论

评论列表(0)

  1. 暂无评论