Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

exports.c_39 = function(req,res) {
    var mongoose = require('mongoose');
    mongoose.createConnection('mongodb://localhost/cj');
    var db = mongoose.connection;
    db.on('error', console.error.bind(console, 'connection error:'));
    console.log('a')
    db.once('open',function(){
        console.log('b')
    })
}

Can perform the console.log (' a '), but cannot perform DB.once ('open') callback function

like image 349
Xingjia Luo Avatar asked May 16 '13 08:05

Xingjia Luo


1 Answers

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
like image 166
robertklep Avatar answered Oct 16 '22 13:10

robertklep