yesterday I started using the javascript MongoDB driver.
I've run into an issue, an error is persistently showing, however, data is still being stored.
Below you can see the javascript I use to initially connect to the DB, and then an insert query is initiated. When not initiating the insert query, the console outputs:
Connected correctly to server
Disconnected from server successfully
But when running with the insert query, an error is returned.
Connected correctly to server
{ [MongoError: server localhost:27017 sockets closed]
name: 'MongoError',
message: 'server localhost:27017 sockets closed'}
Disconnected from server successfully
Could any one point me in the right direction?
MongoClient.connect(db_default.db_url, function(err, db) {
console.log('Connected correctly to server');
if(err) {
console.log(err);
}
else {
mongoInsert(db, 'user', user_default, function(user_res) {
console.log(user_res);
});
}
db.close();
console.log('Disconnected from server successfully');
});
function mongoInsert(db, collection_name, data,cb) {
var collection = db.collection(collection_name);
collection.insert(data, function(err, res) {
if(err) {
console.log(err);
}
else {
console.log('Inserted into the ' + collection_name + ' collection');
cb(res);
}
});
}
Don't Close db connection before receiving results. Do as follow:
MongoClient.connect(db_default.db_url, function(err, db) {
if(err) {
console.log(err);
}
else {
mongoInsert(db, 'user', user_default, function(user_res) {
console.log(user_res);
db.close();
});
}
console.log('Disconnected from server successfully');
});
function mongoInsert(db, collection_name, data,cb) {
var collection = db.collection(collection_name);
collection.insert(data, function(err, res) {
if(err) {
console.log(err);
}
else {
console.log('Inserted into the ' + collection_name + ' collection');
cb(res);
}
});
}
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