1. 程式人生 > 其它 >nodejs mongodb3.6.2 insertOne callback問題

nodejs mongodb3.6.2 insertOne callback問題

npm mongodb包版本:3.6.2

mongodb服務版本:4.0.1

想要模擬一下mongodb服務程序掛掉時,起用備用檔案日誌。

模擬流程:啟動應用時,正常連線mongo,開個10s定時器,寫入mongo資料,在10s內手動停掉mongo服務。

示例程式碼:

const db
= mongodb.db('playlog'); console.log('db2'); try { console.log('collection1'); const collection = db.collection('play_test'); console.log('collection2'); console.log('isConnected:', mongodb.isConnected());
collection.insertOne({ k: 22 }, function(err, result) { console.log(err); });
console.log(
'haha', res); } catch (err) { console.log('got error', err); }

上面程式碼,發現console.log從db2打到haha,但沒有呼叫insertOne函式的callback。

改用await方式:

const db = mongodb.db('playlog');
console.log('db2');
try
{ console.log('collection1'); const collection = db.collection('play_test'); console.log('collection2'); console.log('isConnected:', mongodb.isConnected()); await collection.insertOne({ k: 22 }); console.log('haha'); } catch (err) { console.log('got error', err); }

發現console.log只走到isConnected: false,後續沒任何日誌,catch也沒有日誌。

再改用下面程式碼:

const db = mongodb.db('playlog');
console.log('db2');
try {
   console.log('collection1');
   const collection = db.collection('play_test');
   console.log('collection2');
   console.log('isConnected:', mongodb.isConnected());

   await collection.insertOne({ k: 22 }, function(err, result) {
     console.log(err);
   });

   console.log('haha', res);

} catch (err) {
   console.log('got error', err);
}

這時跟第一種情況一樣,列印到haha,無catch,無insertOne callBack。

換到4.x版本正常,但4.x需要node12.9+版本。線上是10.15,不能隨便升級到4.x,只能自己判斷.