admin管理员组文章数量:1325236
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 badges1 Answer
Reset to default 9You 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
本文标签: javascriptNodejs MongoDB Sockets closed errorStack Overflow
版权声明:本文标题:javascript - Node.js MongoDB Sockets closed error - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742167880a2426166.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论