【问题标题】:Express Mongoose DB.once ('open') cannot execute a callback functionExpress Mongoose DB.once ('open') 无法执行回调函数
【发布时间】:2013-05-11 01:51:51
【问题描述】:
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')回调函数

【问题讨论】:

    标签: express mongoose


    【解决方案1】:

    这是因为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 实例

    【讨论】:

    • 你能告诉我mongoose.connection中的once和on有什么区别吗?
    • @Alexander once 将只调用一次提供的回调,用于发生第一个 open 事件; on每次都会调用提供的回调函数open 事件发生。另请参阅 Node.js 的 events documentation
    【解决方案2】:

    代替mongoose.createConnection 使用: mongoose.connect('mongodb://localhost/cj');

    【讨论】:

      【解决方案3】:

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

      然后使用

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

      【讨论】:

        猜你喜欢
        • 2013-02-22
        • 2017-06-26
        • 1970-01-01
        • 2014-03-20
        • 2016-01-08
        • 1970-01-01
        • 2019-07-15
        • 2018-07-22
        • 2020-08-09
        相关资源
        最近更新 更多