node.js - MongooseServerSelectionError 连接超时后重试
问题描述
我希望我的 nodejs 应用程序在与猫鼬的初始连接失败后重试。我在我的应用程序中连接到两个单独的数据库。以下是供您参考的代码片段。
function makeNewConnection(uri) {
const db = mongoose.createConnection(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverSelectionTimeoutMS: 180000
});
db.on('error', async function (error) {
console.log(`MongoDB :: connection ${this.name} ${JSON.stringify(error)}`);
db.close().catch(() => console.log(`MongoDB :: failed to close connection ${this.name}`));
});
db.on('connected', function () {
mongoose.set('debug', false);
console.log(`MongoDB :: connected ${this.name}`);
});
db.on('disconnected', function () {
console.log(`MongoDB :: disconnected ${this.name}`);
});
return db;
}
const localDBconnection = makeNewConnection(localDB);
const serverDBConnection = makeNewConnection(serverDB);
localDB 和 serverDB 是我的两个连接 uri。如果我超时重试,那么它找不到模型实例。有人可以建议一个干净的方法来做到这一点。
解决方案
推荐阅读
- cytoscape.js - cytoscapeJS 类名选择器覆盖不匹配的类名选择器
- ios - iTunes Connect:更改主要语言的选项不可编辑
- math - 如何在 AMPL 中实现决策变量
- scala - 使用 Apache Spark 为 Kafka 生成 Avro 主题
- python - 使用 Cherrypy 映射特定 url 以响应?
- opencv - 广义霍夫变换 OpenCV Python 的模板
- assembly - 中断问题:定时器、x86、引导扇区、实模式、8295A PIC、8253、汇编
- c# - 我可以使用 InkManager.RecognizeAsync 来识别数学公式吗?
- python-3.x - 在python3.6中反转字符数组
- python - Python Yahoo-Finance Try-Except with Continue for Problem Tickers in a List