Mongoose Connection

后端 未结 5 740
长情又很酷
长情又很酷 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 10:18

    The safest way to do this, it to "listen for the connect event". This way you don't care how long it takes for the DB to give you a connection.

    Once that is done - you should start the server. Also.. config.MONGOOSE is exposed across your app, so you only have one DB connection.

    If you want to use mongoose's connection, simply require config in your module, and call config.Mongoose. Hope this helps out someone!

    Here's the code.

    var mongoURI;
    
    mongoose.connection.on("open", function(ref) {
      console.log("Connected to mongo server.");
      return start_up();
    });
    
    mongoose.connection.on("error", function(err) {
      console.log("Could not connect to mongo server!");
      return console.log(err);
    });
    
    mongoURI = "mongodb://localhost/dbanme";
    
    config.MONGOOSE = mongoose.connect(mongoURI);
    

提交回复
热议问题