Marc Rasmussen Marc Rasmussen - 1 year ago 92
Node.js Question

Does mongodb require connection on each operation

So i am very new to

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() {

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

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download