更新时间:2023-12-04 23:12:28
调用mongoose.connect
时,它将建立与数据库的连接.
When you call mongoose.connect
, it will set up a connection with the database.
但是,您要在更晚的时间点(正在处理请求时)连接open
的事件侦听器,这意味着连接可能已经处于活动状态并且open
事件已经被调用(您只是还没有听).
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).
您应该重新排列代码,以使事件处理程序(及时)尽可能靠近connect调用:
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');
};