2017-06-07 50 views
1

我正在使用nodejs来连接和插入记录在撰写mongodb.I时,我收到以下错误,当我尝试使用insertMany并保存记录。无法使用insertMany插入记录使用撰写为mongodb

(node:10140) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoError: Writes to conf ig servers must have batch size of 1, found 23

下面是我的代码片段:

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(); 
    } 
}); 

回答

0

如果你不使用的承诺无法使用.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}); 
}); 

OR

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

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