When calling mongoose.connect it will establish a connection to the database.
However, you attach an event listener for open at a much later point in time (when the request is processed), which means that the connection is probably already active and the open event has already been raised (you just haven't listened to it yet).
You must change your code so that the event handler is as close as possible (in time) to the connection call:
var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test'); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function callback () { console.log("h"); }); exports.test = function(req,res) { res.render('test'); };
source share