【问题标题】:Unable to insert records using insertMany using compose for mongodb无法使用 insertMany 使用 compose for mongodb 插入记录
【发布时间】:2017-06-13 12:02:24
【问题描述】:

我正在使用 nodejs 为 mongodb 连接和插入记录。当我尝试使用 insertMany 并保存记录时出现以下错误。

(node:10140) UnhandledPromiseRejectionWarning: UnhandledPromiseRejectionWarning: Unhandled Promise Rejection (rejection id: 1): MongoError: Writes to conf ig 服务器的批大小必须为 1,找到 23

下面是我的代码sn-p:

MongoClient.connect(url, function(err, db) {

    if(err){
    console.log('Error is ' + err);
    }
    else{
     console.log("Connected correctly to server");
    try {
    var col = db.collection('offshift');
        col.insertMany(result).then(function(result){
         res.json({message:'Data saved succesfully!',error_code:0, data: result});
       });

    } catch (e) {
       console.log(e);
    }
     db.close();
    }
});

【问题讨论】:

    标签: node.js mongodb compose-db


    【解决方案1】:

    我试图在 Admin 中插入记录。然后我更改了数据库名称并为新数据库创建了具有读/写权限的用户。使用正确的数据库名称和新创建的访问用户更改了我的连接字符串。这解决了问题。

    您可以参考以下链接了解更多详情: https://www.compose.com/articles/avoid-storing-data-inside-admin-when-using-mongodb/

    【讨论】:

      【解决方案2】:

      如果不使用promise就无法使用.then()。因此,您可以使用 callback 函数来代替 .then()。可以试试下面的代码

      var col = db.collection('offshift');
        col.insertMany(result, function(error, result){
             if(error){
                console.log('Error is on insert', error);
              } else
                 res.json({message:'Data saved succesfully!',error_code:0, data: result});
      });
      

      您可以使用返回承诺的.exec(),然后可以使用.then()

      var col = db.collection('offshift');
              col.insertMany(result).exec().then(.....)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-04
        • 1970-01-01
        • 2011-07-05
        • 1970-01-01
        • 1970-01-01
        • 2016-07-02
        • 2016-08-11
        • 1970-01-01
        相关资源
        最近更新 更多