Marc Rasmussen Marc Rasmussen - 3 months ago 13
Node.js Question

Does mongodb require connection on each operation

So i am very new to

mongodb
and i wish to use it in my application. Now i HATE redundant code but reading up on how to use mongodb with node.js it seems that there is a pattern where you always have to connect before making any CRUD operation.

Example from the offical documentation:

MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
insertDocument(db, function() {
db.close();
});
});


My question is. is it possible to make a middleware that keeps the connection open so you only has to call
insertDocument
(in the above example) ?

Answer

Yea of course, just keep the db variable around until you don't need it any longer - then call close()

var mdb;
MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  mdb = db;
  insertDocument(mdb, function() {
      // ...
  });
});

// do other stuff with mdb