Mongoose Connection

后端 未结 5 742
长情又很酷
长情又很酷 2020-12-09 09:31

I read the quick start from the Mongoose website and I almost copy the code, but I cannot connect the MongoDB using Node.js.

var mongoose = require(\'mongoos         


        
5条回答
  •  轮回少年
    2020-12-09 09:58

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

提交回复
热议问题