Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB node.js driver and monk

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.

like image 267
Naresh Avatar asked Dec 12 '13 03:12

Naresh


1 Answers

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.

like image 97
swilson Avatar answered Nov 19 '22 10:11

swilson