node.js – 使用createConnection进行Mongoose连接事件

我暂时不使用默认连接到明确定义的连接.

我的代码工作正常,除了没有跟踪我的mongo连接状态的事件处理程序正在触发.

当我使用默认的mongoose连接时用于触发的事件. (mongoose.connect).

var mongoose = require('mongoose'),
    logger = require('../logger'),
    config = require('../config');  

mongoose.connection.on('connecting', function(){
    logger.info("trying to establish a connection to mongo");
});

mongoose.connection.on('connected', function() {
    logger.info("connection established successfully");
});

mongoose.connection.on('error', function(err) {
    logger.error('connection to mongo failed ' + err);
});

mongoose.connection.on('disconnected', function() {
    logger.log('mongo db connection closed');
})

var gracefulExit = function() {
    db.close(function(){
        logger.log("mongoose connection with db " + server + 'is closing');
        process.exit(0);
    });
};

process.on('SIGNT', gracefulExit).on('SIGTERM', gracefulExit);

var db = mongoose.createConnection(config.get('DB_URL'));
module.exports = db;

代码的问题是

>没有事件处理程序正在触发.
>即使是SIGNT和SIGTERM上的过程事件也没有触发.

我也试过了

var db = mongoose.createConnection(config.get('DB_URL'));

db.on('connecting', function(){
    logger.info("trying to establish a connection to mongo");
});

但这也不会开火.

最佳答案 这段代码对我来说很好

const connection = mongoose.createConnection(`mongodb://${process.env.MONGO_URI}`);

connection.on('connected', () => {
  console.log('connected to mongodb');
});

connection.on('disconnected', () => {
  console.log('connection disconnected');
});
点赞