When you call mongoose.connect
, it will set up a connection with the database.
However, you attach the event listener for open
at a much later point in time (when a request is being handled), meaning that the connection is probably already active and the open
event has already been called (you just weren't yet listening for it).
You should rearrange your code so that the event handler is as close (in time) to the connect call as possible:
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');
};
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…