0

I tried searching on the web and found no obvious code samples of how reuse the mongodb.connection object. This is what I have currently and would anyone please verify if this is okay.

var app = express();
var mongodb = require('mongodb').MongoClient, format = require('util').format;
var db = null;

app.get('/api/v1/put/:var1/:var2', function(req, res){
  collection = db.collection('collection');
  /** .. logic ... **/
});

mongodb.connect('mongodb://127.0.0.1:27017/mydb', function(err, mdb){
    db = mdb;
    app.listen(8000);
});

2 Answers 2

1

Your approach will have problem that once application runs it will register express route. If there is idling connections to your web server, then they will be processed ASAP, that will lead to db is undefined.

In order to prevent this, I would recommend to register express routing only after database is connected.
As well you can cache collections instead of getting them on each request.

Sign up to request clarification or add additional context in comments.

2 Comments

Do you mean by putting app.get inside mongodb.connect ?
Exactly. Put route definition inside of database connect callback. In fact you could even tidy it up, and have global event that you can reuse all around that will be triggered on connect to db.
1

this is just to refactor my question's code to reflect Maksims' suggestion

var app = express();
var mongodb = require('mongodb').MongoClient, format = require('util').format;

mongodb.connect('mongodb://127.0.0.1:27017/mydb', function(err, db){
    collection = db.collection('collection');

    app.get('/api/v1/put/:var1/:var2', function(req, res){
      /** .. logic ... **/
    });

    app.listen(8000);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.