Note that there are some explanatory texts on larger screens.

plurals
  1. POKeeping open a MongoDB database connection
    text
    copied!<p>In so many introductory examples of using MongoDB, you see code like this:</p> <pre><code>var MongoClient = require('mongodb').MongoClient; MongoClient.connect("mongodb://localhost:port/adatabase", function(err, db) { /* Some operation... CRUD, etc. */ db.close(); }); </code></pre> <p>If MongoDB is like any other database system, <code>open</code> and <code>close</code> operations are typically expensive time-wise. </p> <p>So, my question is this: Is it OK to simply do the <code>MongoClient.connect("...</code> once, assign the returned <code>db</code> value to some module global, have various functions in the module do various database-related work (insert documents into collections, update documents, etc. etc.) when they're called by other parts of the application (and thereby re-use that <code>db</code> value), and then, when the application is done, only then do the <code>close</code>. </p> <p>In other words, <code>open</code> and <code>close</code> are done once - not every time you need to go and do some database-related operation. And you keep re-using that <code>db</code> object that was returned during the initial <code>open\connect</code>, only to dispose of it at the end, with the <code>close</code>, when you're actually done with all your database-related work. </p> <p>Obviously, since all the I/O is asynch, before the <code>close</code> you'd make sure that the last database operation completed before issuing the <code>close</code>. Seems like this should be OK, but i wanted to double-check just in case I'm missing something as I'm new to MongoDB. Thanks!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload