Wednesday, February 15, 2017

MongoDB Node.js Driver Connection Management

Connection management features such as connection pool are common in any frameworks used with Java and MySQL. In this post, I will introduce how to implement the connection management with Node.js and MongoDB.

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

No comments:

Post a Comment