阅读 61

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,只能自己判断.

 

原文:https://www.cnblogs.com/cool-fire/p/15266973.html

文章分类
百科问答
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐