Express Mongoose DB.once ('open') cannot execute a callback function

That's because mongoose.connection isn't the same as the connection that is returned by createConnection().

There are two ways of opening a connection with Mongoose:

// method 1: this sets 'mongoose.connection'
> var client = mongoose.connect('mongodb://localhost/test');
> console.log(client.connection === mongoose.connection)
true

// method 2: this *doesn't* set 'mongoose.connection'
> var connection = mongoose.createConnection('mongodb://localhost/test');
> console.log(client.connection === mongoose.connection)
false

So to solve your problem, you need to connect your event handler to the connection as returned by createConnection(), and not to mongoose.connection:

var db = mongoose.createConnection('mongodb://localhost/cj');
db.once('open', function() { ... });

In short:

  • .createConnection() returns a Connection instance
  • .connect() returns the global mongoose instance