zoukankan      html  css  js  c++  java
  • 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,只能自己判断.

  • 相关阅读:
    sharepoint具体错误提示
    体验魅力Cognos BI 10 系列,第1 部分: 第一次安装
    Moss、SharePoint数据库迁移问题(转)
    XML解析
    JDBC进阶
    JDBC的操作
    项目Contact开发中遇到的,引以为戒
    递归练习
    递归详解(四)
    递归详解(三)
  • 原文地址:https://www.cnblogs.com/cool-fire/p/15266973.html
Copyright © 2011-2022 走看看