Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) ?

like image 558
Marc Rasmussen Avatar asked Feb 25 '26 19:02

Marc Rasmussen


2 Answers

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
like image 71
tengobash Avatar answered Feb 27 '26 09:02

tengobash


You can also look into using Mongoose as you mentioned middleware.

The connection is only opened once (on the global scope) and then you can use it throughout the app.

like image 30
realtimez Avatar answered Feb 27 '26 11:02

realtimez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!