2
votes

I'm using the node-mongodb-native to connect to a local MongoDB instance. I'm having a little trouble wrapping my head around how to handle the connections. I've attempted to abstract the MongoDB stuff into a custom Database module:

Database.js

var mongo = require('mongodb'); 
var Database = function() { return this; };

Database.prototype.doStuff = function doStuff(callback) {
    mongo.connect('mongodb://127.0.0.1:27017/testdb', function(err, conn) {
        conn.collection('test', function(err, coll) {
            coll.find({}, function(err, cursor) {
                cursor.toArray(function(err, items) {
                    conn.close();
                    return callback(err, items);
                });
            });
        });
    });
};

// Testing
new Database().doStuff(function(err, items) {
    console.log(err, items);
});

Is a new connection required for each method? That seems like it would get expensive awfully quick. I imagined that perhaps the connection would be established in the constructor and subsequent calls would leverage the existing connection.

This next question may be more of a design question, but considering how connection setup and tear-down may be expensive operations, I'm considering adding a Database object that is global to my application that can be leveraged to make calls to the database. Does this seem reasonable?

Please note that the code above was roughly taken from here. Thanks for your help.

1

1 Answers

2
votes

You don't need a new connection for each method - you can open it once and use it for subsequent calls. The same applies to the individual collection variables - you can cache the result of a single call to collection() and this will let you only need those callbacks once, leaving them out everywhere else.