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?
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
});
});
}