Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
2 views
in Web Technology by (47.6k points)

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 the server

Disconnected from server successfully

But when running with the insert query, an error is returned.

Connected correctly to the server

{ [MongoError: server localhost:27017 sockets closed]

name: 'MongoError',

message: 'server localhost:27017 sockets closed'}

Disconnected from server successfully

Could anyone 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); 

}); 

}

2 Answers

0 votes
by (106k points)

To get rid of this problem you can use the below-mentioned code:-

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

}); 

}

0 votes
by (108k points)

The problem was file security on the new server and MongoDB npm files, you have to use "chown" command to own all files and then run "npm install"

Related questions

0 votes
2 answers
asked Oct 17, 2019 in Web Technology by Sammy (47.6k points)
0 votes
2 answers
0 votes
1 answer
asked Feb 16, 2020 in Web Technology by ashely (50.2k points)
0 votes
1 answer
asked Feb 9, 2020 in Web Technology by ashely (50.2k points)

Browse Categories

...