3

I'm writing some simple web app with Node.JS and want to use mongoDB as main data storage.
Node-mongodb-native driver requires to make chained calls before you actually can query or store data (open DB connection, authenticate, get collection).
Where is the best place to do this initialization - within each request handler or globally, when initializing application?

1 Answer 1

2

You are MUCH better putting the Mongo initialization outside of your request handler - otherwise it will re-connect for every page that is served:

var mongo = require('mongodb');

// our express (or any HTTP server)
var app = express.createServer();

// this variable will be used to hold the collection for use below
var mongoCollection = null;

// get the connection
var server = new mongo.Server('127.0.0.1', 27017, {auto_reconnect: true});

// get a handle on the database
var db = new Db('testdb', server);
db.open(function(error, databaseConnection){
    databaseConnection.createCollection('testCollection', function(error, collection) {

      if(!error){
        mongoCollection = collection;
      }

      // now we have a connection - tell the express to start
      app.listen(80);

    });
});

app.use('/', function(req, res, next){
    // here we can use the mongoCollection - it is already connected
    // and will not-reconnect for each request (bad!)
})
Sign up to request clarification or add additional context in comments.

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.