在猫鼬中重新连接到副本的问题

时间:2019-05-24 14:09:40

标签: javascript node.js mongodb mongoose

这样的问题。 有一个副本,由三个成员组成。 一小学,二中学。 主:带27001端口 由于某种原因,命令rs.stepDown()正在重新连接到27001,尽管它已经是第二个了。 我不明白为什么。

我使用最新的猫鼬和MongoDB。

Connection established to MongoDB to port: 27001 db3 
connected 
Lost MongoDB connection... 
Connection established to MongoDB to port: 27001 db3 
Reconnected to MongoDB
const uri = 'mongodb://localhost:27001,localhost:27002,localhost:27003';

var isConnectedBefore = false;

var connect = function() {
    mongoose.connect(uri, 
        {dbName: 'db3', useNewUrlParser: true, 
        server: 
            { 
                auto_reconnect: true, 
                reconnectTries : Number.MAX_VALUE,
                reconnectInterval: 1000
            },
        replSet: 
            {
                replicaSet: 'myreplica'
            }
        });
};

connect();

var db = mongoose.connection;


db.on('error', function() {
    console.log('Could not connect to MongoDB');
});

db.on('disconnected', function(){
    console.log('Lost MongoDB connection...');
    if (!isConnectedBefore)
        connect();
});

db.on('connected', function() {
    isConnectedBefore = true;
    var db = mongoose.connection;
    console.log(db);
    console.log('Connection established to MongoDB to port: ' + db.port + " " + db.name);
});

db.on('reconnected', function() {
    console.log('Reconnected to MongoDB');
});

process.on('SIGINT', function() {
    mongoose.connection.close(function () {
        console.log('Force to close the MongoDB conection');
        process.exit(0);
    });
});

db.once('open', function () {
    console.log('connected');
});

0 个答案:

没有答案