Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

express: keep all DRY creating a mongoose connection module (using the new createConnection method)

express: keep all DRY creating a mongoose connection module (using the new createConnection method)

Problem

Here's my actual db connection module:

var mongoose = require('mongoose'),
  conn = mongoose.createConnection('localhost', 'doto');

conn.on('error', function (err) {
  console.log('Error! DB Connection failed.');
});

conn.once('open', function () {
  console.log('DB Connection open!');
});

module.exports = conn;

and there's a place where I use it

exports.list = function (req, res) {
  var conn = require('../lib/db_connection');

  conn.once('open', function () { // if i dont wrap with this, the page will not be rendered...
    conn.db.collectionNames(function (err, names) {
      res.render('list_collections', {
        title: 'Collections list',
        collections_names: names
      });
    });
  });
}

My question is: I really need to use conn.once every time? Any suggestion?

Problem courtesy of: cl0udw4lk3r

Solution

You should move the require outside of your function so that the connection is opened when your application loads instead of waiting until the first request.

var conn = require('../lib/db_connection');
exports.list = function (req, res) {
  conn.db.collectionNames(function (err, names) {
    res.render('list_collections', {
      title: 'Collections list',
      collections_names: names
    });
  });
}
Solution courtesy of: JohnnyHK

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

express: keep all DRY creating a mongoose connection module (using the new createConnection method)

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×