当前接受的答案是正确的,因为您可以保持相同的数据库连接打开以执行操作,但是,它缺少有关在关闭时如何重试连接的详细信息。以下是自动重新连接的两种方法。它在 TypeScript 中,但如果需要,它可以很容易地转换成普通的 Node.js。
方法一:MongoClient 选项
允许 MongoDB 重新连接的最简单方法是在将 areconnectTries
传递options
到MongoClient
. 任何时候 CRUD 操作超时,它都会使用传入的参数MongoClient
来决定如何重试(重新连接)。将选项设置为Number.MAX_VALUE
实质上使其永远重试,直到它能够完成操作。如果您想查看将重试哪些错误,可以查看驱动程序源代码。
class MongoDB {
private db: Db;
constructor() {
this.connectToMongoDB();
}
async connectToMongoDB() {
const options: MongoClientOptions = {
reconnectInterval: 1000,
reconnectTries: Number.MAX_VALUE
};
try {
const client = new MongoClient('uri-goes-here', options);
await client.connect();
this.db = client.db('dbname');
} catch (err) {
console.error(err, 'MongoDB connection failed.');
}
}
async insert(doc: any) {
if (this.db) {
try {
await this.db.collection('collection').insertOne(doc);
} catch (err) {
console.error(err, 'Something went wrong.');
}
}
}
}
方法二:Try-catch Retry
如果您想在尝试重新连接时获得更精细的支持,可以使用带有 while 循环的 try-catch。例如,您可能希望在必须重新连接时记录错误,或者您希望根据错误类型执行不同的操作。这也将允许您根据更多条件重试,而不仅仅是驱动程序随附的标准条件。该insert
方法可以更改为以下内容:
async insert(doc: any) {
if (this.db) {
let isInserted = false;
while (isInserted === false) {
try {
await this.db.collection('collection').insertOne(doc);
isInserted = true;
} catch (err) {
// Add custom error handling if desired
console.error(err, 'Attempting to retry insert.');
try {
await this.connectToMongoDB();
} catch {
// Do something if this fails as well
}
}
}
}
}