Node.js 使用路由器打开mongoose连接。在express 4.0中使用

Node.js 使用路由器打开mongoose连接。在express 4.0中使用,node.js,mongodb,express,mongoose,Node.js,Mongodb,Express,Mongoose,我正在将我的代码从monk转换为mongoose。 我已使用路由器中间件打开了与mongodb的连接: //use router middleware to connect to mongodb using mongoose router.use(function(req,res,next){ mongoose.connect('mongodb://localhost/takenote'); //take a look here to figure out how to handle

我正在将我的代码从
monk
转换为
mongoose
。 我已使用
路由器
中间件打开了与
mongodb
的连接:

//use router middleware to connect to mongodb using mongoose
router.use(function(req,res,next){
  mongoose.connect('mongodb://localhost/takenote');

  //take a look here to figure out how to handle mongoose connection:
  //http://theholmesoffice.com/mongoose-connection-best-practice/
  mongoose.connection.on('error',function(err){
    if(err)
      console.error(err);
  });
  mongoose.connection.on('connected',function(){
    console.log('connection established');
  });

  mongoose.connection.on('disconnected',function(){
    console.log('Disconnected from mongo db');
  });

  mongoose.connection.on('SIGINT',function(){
    //sigint represents the termination of the app
    mongoose.connection.close(function(){
      console.log("Connection to mongo db has been closed because the app terminated");
      process.exit(0);
    });
  });
  next();
});
我使用这里定义的
路由
调用
猫鼬
方法:

router.get('/main',function(req,res){
   var locals={};
   locals.title="TakeNote:An easy to use note taking app for web and hopefully mobile";
   locals.sidebar={};
   locals.sidebar.items=[];
   locals.notebook={};
   locals.notebook.notes=[];

   notebook
   .find()
   .populate('notes')
   .exec(function(err,docs){
      _(docs).forEach(function(notebook){
          locals.sidebar.items.push(notebook.title);
          locals.notebook.notes=notebook.notes;
          res.render('main',locals);    
     });
  });   
});
我在调用任何路由时出错:

  { [Error: Trying to open unclosed connection.] state: 1 }

如何解决此问题?将
mongoose
连接放置在
路由器
中间件中是否有问题

不要那样做。在应用程序启动代码期间打开
mongoose
连接。它是一个连接池,旨在由所有请求共享,并在应用生命周期内保持打开状态