unhurried

コンピュータ関連ネタがほとんど、ときどき趣味も…

MongoDB Node.js Driver Connection Management

Points

  • Call MongoClient.connect only once, and reuse the instance.
  • Connection management is done by the driver and the number of connections can be specified in the option of MongoClient.connect.

Sample Code

  • db.js
// Keep the mongoDB connection while the application is running.
var db = null;
module.exports.initialize = co.wrap(function*() {
    db = yield MongoClient.connect("mongodb://...");
});

module.exports.getById = co.wrap(function*(id) {
var col = db.collection("collection");
    var row = yield col.findOne({_id:id});
    return row.property;
});
  • app.js
var db = require('./db');

co(function*(){
    db.initialize();
    var result = db.getById(0);
    ...
});

Reference