VorpalSword
VorpalSword

Reputation: 1293

Whats an efficient, correct way of using monk / mongo in express middleware?

I have a web app under development. I found CW Buechler's tutorial on how to make a simple one very useful but have a couple of niggling worries that I'd like to know whether they're real issues, or things I can ignore.

The way I connect my routes to my database is straight from the tutorials.

in app.js, this code instantiates the database, and attaches a reference to it to every req object that flows thru the middleware.

// wire up the database
var mongo = require('mongodb');
var db = require('monk')('localhost:27017/StarChamber');

----------8<-------

// Make our db accessible to our router
app.use(function(req,res,next){
    req.db = db;
    next();
});

And in the middleware it get used like this:

app.get('/', function (req, res) {
    var db = req.db;
    var collection = db.get('myCollection');
    // do stuff to produce results
    res.json (results);
});

So, to my niggling worries:

  1. Passing the db to the routes by attaching it to the req is pretty convenient, but does it impact performance? Would it be better to have a reference to it in my router file that I could just use? What's the code to do this?
  2. Is it good practice to drop the collection after its been used? The Tutorial doesn't do so, but a collection.drop() call before exiting the route handler looks beneficial, otherwise I think I'll just rack up lots of open connections with the db.

Thanks as ever!

Upvotes: 2

Views: 998

Answers (1)

robertklep
robertklep

Reputation: 203359

  1. No, it won't impact performance. It's a convenient method to pass a reference to db around, but with Monk it doesn't seem to be especially necessary. See below for an alternative setup.
  2. You are confusing collections with connections. The former are the MongoDB-equivalent of "tables" in SQL, so dropping them doesn't seem to make sense since that would basically throw away all the data in your database table. As for connections: through various layers of indirection, Monk seems to be using the official MongoDB Node driver, which handles connections itself (by means of a connection pool). So there's no need to handle it yourself.

For an alternative way of passing the Monk database handle around: you can place it in a separate module:

// database.js
module.exports = require('monk')('localhost:27017/StarChamber');

And in each module where you require the handle, you can import it:

var db = require('./database');

Upvotes: 5

Related Questions