8

I am using the mongodb driver and monk on nodejs. Examples such as this that I see on the Web have the following pattern:

var mongo = require('mongodb');
var monk = require('monk');

var db = monk('localhost:27017/userdb');
var collection = db.get('users');
collection.find({}, function(err, docs) {
    // do something with docs
});

Two questions:

  1. Why is the first line needed: var mongo = require('mongodb')? The variable mongo is never used. Wouldn't monk automatically require mongodb?
  2. I see at the driver level, the db has to be opened and closed. These methods don't seem to exist at the monk level. Does monk automatically open and close connections? How does this work?

As a matter of fact, I am wondering what advantage does monk provide over using the driver directly. I read the list of features in the monk docs, but don't really understand the benefits.

Thanks in advance for your help.

Naresh
  • 23,937
  • 33
  • 132
  • 204

1 Answers1

6

To answer some of the specifics, based on my own experience:

1) You are correct that the mongodb variable is not required. I don't know why it appears in all the tutorials. However, mongodb IS required as a dependency, additional to monk.

2) As you suspected, you do need to call db.close(), otherwise the connection stays open. This doesn't seem to be documented anywhere. When you follow that tutorial you can see the number of open connections to your local mongodb growing.

As you've probably read already, the goal of monk is to provide a friendlier API than mongodb's own driver. I don't have enough experience with it to say whether or not it achieves that.

swilson
  • 471
  • 4
  • 9
  • 1
    Regarding #1 - by requiring mongodb separately, you have control over the version of mongodb. You might be using a local OR global version of mongodb, you might be using an older version or even a newer beta version. If monk required mongo on its own, you wouldn't have control over which installation or version it used. – Ryan Wheale Jan 16 '14 at 01:18
  • It looks like you shouldn't worry about closing your connection. http://stackoverflow.com/questions/14495975/why-is-it-recommended-not-to-close-a-mongodb-connection-anywhere-in-node-js-code – reergymerej Jan 21 '14 at 17:41
  • @blurd In this particular case, mongoDB doesn't re-use the ones you leave open, so the code above is opening an ever-increasing number of connections and leaving them open. However, I do completely agree that it's much better to open and reuse one connection (or a small pool of connections) than to open and close a new connection for each DB interaction. – swilson Mar 18 '14 at 02:53