4

Mongo documentation shows how to setup a connection pool when MongoClient and server are defined in same module:

var express = require('express');
var mongodb = require('mongodb');
var app = express();

var MongoClient = require('mongodb').MongoClient;
var db;

// Initialize connection once
MongoClient.connect("mongodb://localhost:27017/integration_test", function(err, database) {
  if(err) throw err;

  db = database;

  // Start the application after the database connection is ready
  app.listen(3000);
  console.log("Listening on port 3000");
});

// Reuse database object in request handlers
app.get("/", function(req, res) {
  db.collection("replicaset_mongo_client_collection").find({}, function(err, docs) {
    docs.each(function(err, doc) {
      if(doc) {
        console.log(doc);
      }
      else {
        res.end();
      }
    });
  });
});

How does this work when you have, say, an app.js that sets up the server and an api.js that defines the routes?

Evan Zamir
  • 8,059
  • 14
  • 56
  • 83

1 Answers1

3

One easy solution is to write some simple middleware in app.js to pass it along to the routes via the request variable.

app.use(function(req, res, next) {
    req.db = db;
    next();
});

All of your routes will, of course, have access to req and res, so they can access it through req.db.

Josh1billion
  • 14,837
  • 8
  • 38
  • 48
  • In this scenario, I assume the MongoClient connection should be defined before the middleware? – Evan Zamir Jan 14 '16 at 18:55
  • That works, but it shouldn't matter whether you put it before or after, because the middleware function being passed to app.use() will be executed fresh every time an HTTP request happens, not just once when the application starts up. So, by the time any HTTP requests happen and the middleware function starts getting called, `db` will have already been assigned by the `db = database;` line in your post. – Josh1billion Jan 14 '16 at 20:22
  • 1
    @Josh1billion, thanks dude this really helped me. – Vaibhav Bisht Jan 04 '22 at 14:35
  • @VaibhavBisht glad to hear that – Josh1billion Jan 12 '22 at 04:13