【问题标题】:What is the syntax for detecting Mongoose events?检测 Mongoose 事件的语法是什么?
【发布时间】:2018-10-24 13:48:28
【问题描述】:

我想根据猫鼬文档here检测打开事件:

连接后,会在 Connection 实例上触发 open 事件。如果 您正在使用 mongoose.connect,连接是 mongoose.connection。 否则,mongoose.createConnection 返回值为一个 Connection。

我正在使用 mongoose.connect,所以我想它是这样的

mongoose.connection.on('open', () => {
  console.log('connected!');
})

但我不确定。

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    当您打开连接时,有两个事件需要在连接打开时监听,这仅在我们使用时发生:

    mongoose.connection.once('open', function() {
      // we're connected!
    });
    

    可能发生在任何时间且不止一次的错误事件:

    mongoose.connection.on('error', console.error.bind(console, 'connection error:'));
    

    查看文档mongoose

    【讨论】:

      【解决方案2】:

      试试这个并检测 Mongoose 事件。

      const mongoose = require('mongoose');
      const URI = 'connection path';
      
      mongoose.connect(process.env.MONGODB_URI || URI, { useNewUrlParser: true });
      
      // When successfully connected
      mongoose.connection.on('connected', () => {
          console.log('Established Mongoose Default Connection');
      });
      
      // When connection throws an error
      mongoose.connection.on('error', err => {
          console.log('Mongoose Default Connection Error : ' + err);
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-08-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-27
        • 1970-01-01
        相关资源
        最近更新 更多