4

I am saving a document to the db with the following code:

MongoClient.connect(mongoUrl, function(error, db) {
    console.log('Mongo: error = \'' + error + '\' db = \'' + db + '\'');
    insertDocument(db, parsedDocument);
    db.close();
});

function insertDocument(db, document) {
    db.collection('test').insertOne(document, function(error, result) {
        console.log('Save document.  error = \'' + error + '\' result = \'' + result + '\'');
    });
}

However, if I leave the db.close() statement in I get the an error in the error object. If I remove the line then the document is saved.

Received.  ID: '04023828-9ef3-4f10-b1d1-108208c9e3b7'
Mongo: error = 'null' db = '[object Object]'
Save document.  error = 'MongoError: server localhost:27017 sockets closed' result = 'undefined'
  1. Why is closing the db causing an error?
  2. Is it safe to not explicitly close the connection?
BanksySan
  • 27,362
  • 33
  • 117
  • 216
  • @BlakesSeven It's really not, this was a problem with MongoDB and the solution was that I hadn't realised a method was asynchronous. The other question is an example of various asynchronous techniques. – BanksySan Nov 13 '15 at 10:16
  • It "really is". You failed to respect that the preceeding operations are asychronous and hence failed to repect that they have not completed by your call of close. Which is exactly what the answer you accepted says. But it's still a duplicate, and why it has been marked as such. This helps others understand the real context. – Blakes Seven Nov 13 '15 at 10:21

1 Answers1

5

1. Why is closing the db causing an error?

Your function insertDocument is executed asynchronously. You are not waiting for the insertion to finish and execute db.close() right away, which naturally interferes with the insert operation.

If you need to close the connection, do it in a callback that you pass to insertDocument.

2. Is it safe to not explicitly close the connection?

You should actually try to reuse your connection throughout your application lifetime. See this comment by a major contributor to the Node driver: https://groups.google.com/d/msg/node-mongodb-native/mSGnnuG8C1o/Hiaqvdu1bWoJ

Also, read up on connection pooling: https://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html#mongoclient-connection-pooling

Dmytro Shevchenko
  • 33,431
  • 6
  • 51
  • 67