Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat's the best practice for MongoDB connections on Node.js?
    primarykey
    data
    text
    <p>This is something that is a bit unclear to me (I'm just getting started with Node and Mongo), and it really concerns me because of server performance and strain (which I guess is another question, but I'll get to that at the end of the post).</p> <p>So, assuming I'm writing an API with Node.js and Restify, where each API endpoint corresponds to a function, should I:</p> <p><strong>a)</strong> open the db connection and store it in a global var, and then just use that in every function?<br> Example:</p> <pre><code>// requires and so on leave me with a db var, assume {auto_reconnect: true} function openDB() { db.open(function(err, db) { // skip err handling and so on return db; } } var myOpenDB = openDB(); // use myOpenDB in every other function I have </code></pre> <p><strong>b)</strong> open the db connection and then just put everything in one giant closure?<br> Example:</p> <pre><code>// same as above db.open(function(err, db) { // do everything else here, for example: server.get('/api/dosomething', function doSomething(req, res, next) { // (server is an instance of a Restify server) // use the db object here and so on }); } </code></pre> <p><strong>c)</strong> open and close the db each time it is needed?<br> Example:</p> <pre><code>// again, same as above server.get('/api/something', function doSomething(req, res, next) { db.open(function(err, db) { // do something db.close(); }); }); server.post('/api/somethingelse', function doSomethingElse(req, res, next) { db.open(function(err, db) { // do something else db.close(); }); }); </code></pre> <p>This last one is what I would do out of intuition, but at the same time I don't feel entirely comfortable doing this. Doesn't it put too much strain on the Mongo server? Especially when (and I hope I do get to that) it gets hundreds — if not thousands — of calls like this?</p> <p>Thank you in advance.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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