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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With