Search code examples
node.jsmongodbmongoose

Mongoose Connection


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('mongoose');
mongoose.connect('mongodb://localhost/test');

exports.test = function(req, res) {
  var db = mongoose.connection;
  db.on('error', console.error.bind(console, 'connection error:'));
  console.log("h1");
  db.once('open', function callback () {
    console.log("h");
  });
  res.render('test');
};

This is my code. The console only prints h1, not h. Where am I wrong?


Solution

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