2016-03-05 127 views
4

我目前正在爲我的NodeJS應用程序製作登錄系統。然而,每當我嘗試檢索一個集合時,我都會從MongoDB中得到一個奇怪的錯誤。Node.js MongoDB套接字關閉錯誤

錯誤消息

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

繼承人我的代碼連接到我的分貝

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(); 
    }); 

是任何人都能夠看到伊夫了什麼問題?在先進的感謝:)

回答

7

你正在關閉自己的數據庫之前查找查詢完成(這是一個異步方法)。刪除db.close()或在findOne回調中移動它。

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(); 
    }); 


}); 

順便說一句,你將可以通過連接/每個查詢的關閉數據庫連接並且你應該避免這樣做,有非常差的性能:在應用程序啓動時連接,然後再關閉應用上的接近分貝

+0

:0非常感謝! 「垃圾郵件接受按鈕」:) –