現在受け入れられている回答は、操作を実行するために同じデータベース接続を開いたままにしておくことができるという点で正しいですが、閉じた場合に接続を再試行する方法に関する詳細が欠落しています。以下に、自動的に再接続する 2 つの方法を示します。これは TypeScript ですが、必要に応じて通常の Node.js に簡単に変換できます。
方法 1: MongoClient オプション
MongoDB が再接続できるようにする最も簡単な方法は、 に渡すときに を で定義するreconnectTries
こと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.');
}
}
}
}
方法 2: try-catch リトライ
再接続の試行についてより詳細なサポートが必要な場合は、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
}
}
}
}
}