Mongodb节点在重新连接时创建大量连接

时间:2018-07-05 10:34:26

标签: node.js mongodb

我有这个脚本,与Mongo的连接非常简单。如果与数据库的连接丢失,则恢复连接后将与数据库建立大量连接。您知道我的代码或库中是否存在错误? 我也用猫鼬测试过,但我有同样的问题。

var mongodb = require('mongodb').MongoClient;
var options = {
useNewUrlParser: true,
autoReconnect: true,
poolSize: 3,
reconnectTries: Number.MAX_VALUE,
reconnectInterval: 1000
}
var conectDate = new Date();
var count = 0;

// Connect to the db
mongodb.connect(url, options, function (err, db) {
if (!err) {
console.log("We are connected");
db.on('close', function () {
    console.log('Close')
})
db.on('reconnect', function () {
    console.log('Reconnect')
})
}
}

猫鼬代码

var mongoose = require('mongoose');

var url = 'mongodb://localhost:28410/colection';
var options = {
autoReconnect: true,
poolSize: 3,
reconnectTries: Number.MAX_VALUE,
reconnectInterval: 1000
};

mongoose.connect(url, options, function (err) {
if (!err) {
    mongoose.connection.on('disconnected', function () {
    var currentDate = '[' + new Date().toUTCString() + '] ';
    console.log(currentDate + 'Mongo disconnected');
});

mongoose.connection.on('connected', function () {
    var currentDate = '[' + new Date().toUTCString() + '] ';
    console.log(currentDate + 'Mongo connected');
});

}
})

2 个答案:

答案 0 :(得分:0)

您可以像下面这样简单地进行操作:

// Lets build Mongo Connection String based on environment information
const connectionString =  "mongodb://" + DBOptions.user + ":" + encodeURIComponent(DBOptions.pass) + "@" + DBOptions.url +
                          ":" + DBOptions.port + "/" + DBOptions.dbName + "?" +
                          "ssl=" + DBOptions.ssl + "&replicaSet=" + DBOptions.replicaSet;

//const localString = 'mongodb://localhost:27017/BusinessDev';
// Connect to MONGO INSTANCE!!!!
mongoose.connect(connectionString,{
  useMongoClient: true,
}).catch((e) => {
    logger.error('Error in connect with mongo client',e);
});


mongoose.connection.on('connected', function () {
    logger.info(chalk.underline(`APP MONGODB@${mongoose.version}:`) );
});

mongoose.connection.on('disconnected', function () {
    logger.info(`Mongoose disconnected to: ${chalk.red.bold(DBOptions.dbName)}`);
});

process.on('SIGINT', function () {
    logger.info(chalk.red.bold('\nMongoose disconnected through app termination\n'));
    process.exit(0);
});

答案 1 :(得分:0)

这不是代码错误,它像Mongodb核心和mongoose中的错误一样被接受。