使用猫鼬为不同的数据库创建2个连接

时间:2019-07-18 08:21:23

标签: node.js mongoose

我正在使用node.js,并且试图用mongoose创建两个连接,并为它们创建重试函数和模型。

直到现在,我使用mongoose.connect(url,options)处理了一个连接, 此连接保存在猫鼬中,每次我想使用该连接时,我只是在调用猫鼬。

我的问题是当我尝试创建另一个连接时。 我正在使用mongoose.createConnection(url),但是如果我重试,我不知道如何获得有效的连接。 我知道它保存在mongoose.connections下,但是有更多的连接而不是打开的(重试中的关闭连接我无法连接..)

这是我的连接和重试功能-

  return  mongoose.connect(config.db_url, options, function(err){
    if(err){
      mongoose.disconnect();
      console.error('Failed to connect to mongo db. Retrying');
      setTimeout(connectWithRetry, 5000);
    }
    else{
      firstConnect = false;
    }
  });
};

var connectWithRetry = function() {
  return  mongoose.createConnection(config.db_url, options, function(err){
    if(err){
      mongoose.connections[mongoose.connections.length-1].close();
      console.error('Failed to connect to mongo db. Retrying');
      setTimeout(connectWithRetry, 5000);
    }
    else{
      firstConnect = false;
    }
  });
};

0 个答案:

没有答案