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
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
instanceIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With