无法使用insertMany插入记录使用撰写为mongodb
问题描述:
我正在使用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();
}
});
答
我试图插入记录在管理。然后我更改了数据库名称并创建了具有新数据库读/写权限的用户。使用正确的数据库名称和新创建的用户访问权限更改了我的连接字符串。这解决了这个问题。
您可以参考以下链接了解更多详情: https://www.compose.com/articles/avoid-storing-data-inside-admin-when-using-mongodb/
答
如果你不使用的承诺无法使用.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(.....)