Following instructions from MongoHQ's documentation, I installed node-mongodb-native using npm:
npm install mongodb
I then proceeded to connect to the database as stated in the instructions, using:
var mongodb = require('mongodb');
mongodb.Db.connect(process.env.MONGOHQ_URL, function(error, client) {
// do whatever here with client
});
It works fine, both locally and on heroku. But I can't find any documentation regarding this connect
method. I looked in many places:
Yet I can't find anything concerning the connect
method...
I believe Db.open
is the more common command. I'm not sure where they got Db.connect
, which looks like an internal function that gets called by open: https://github.com/christkv/node-mongodb-native/blob/master/lib/mongodb/db.js#L250
See plenty of uses of open
in the following test:
https://github.com/christkv/node-mongodb-native/blob/master/test/db_test.js
That aside, I would recommend setting up a connection pool if you plan to do multiple things at the same time (which sometimes happens "accidentally" with the async nature of node), examples of which can be seen in the tests: https://github.com/christkv/node-mongodb-native/blob/master/test/connection/connection_pool_test.js
You are right the connect method is not documented properly in the sense that the url format is missing. I'll make sure to address that as soon as I can. I guess I overlooked it a bit since it was a contrib.
DO NOT call open on each request. Opening a new connection to mongodb means a new socket connection and thread on the server allocating 1MB of ram causing more context switches and potentially causing you to flood mongodb with connections.
Create one db instance with a poolSize:N and reuse it everywhere.
I'm currently taking the NODE/MONGO course developers and there they only use the db.connect as:
MongoClient.connect('mongodb://localhost:27017/blog', function(err, db) {});
this code is being used as the Main loop where the 'db' database handle is created once and used everywhere else in the application code.