1

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?

cl0udw4lk3r
  • 2,663
  • 5
  • 26
  • 46
  • No, you shouldn't need to use `conn.once` every time. What specifically happens if you omit that? – JohnnyHK Nov 02 '12 at 21:58
  • Simply no "list_collections" view is rendered... when I send my request (typing localhost:3000/list_collections) I never get a response... (Sry again for my bad english.) – cl0udw4lk3r Nov 03 '12 at 09:19

1 Answers1

1

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
    });
  });
}
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471