Express Mongoose DB.once('open')无法执行回调函数

时间:2013-05-16 08:47:44

标签: express mongoose

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

可以执行console.log('a'),但无法执行DB.once('open')回调函数

3 个答案:

答案 0 :(得分:11)

那是因为mongoose.connectioncreateConnection()返回的连接不同。

有两种方法可以打开与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

因此,要解决您的问题,您需要将事件处理程序连接到createConnection()返回的连接,而不是mongoose.connection

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

简而言之:

  • .createConnection()返回Connection个实例
  • .connect()返回全局mongoose实例

答案 1 :(得分:1)

而不是mongoose.createConnection使用: mongoose.connect('mongodb://localhost/cj');

答案 2 :(得分:0)

db=  mongoose.createConnection('mongodb://localhost/cj'). 

然后使用

db.on("connected", connected); with connected = err => {
  console.log(`connected ${db.readyState}`);
};