我有一個for循環插入文件在MongoDB中。使用異步系列我運行五次循環,然後關閉連接。由於一些奇怪的原因,當第六次執行循環時,我得到一個插入錯誤。我只是不確定這裏發生了什麼。有任何想法嗎?插入錯誤使用node.js異步系列
var mycollection= "abcd";
var count = 5;
var db;
var col;
async.series([
// Connect to DB
function(callback) {
MongoClient.connect("mongodb://connection-path-here",function(error, db2) {
if (error) {console.log("db connect error");callback(error,"db connect error"); return;}
db = db2;
callback(null,"connect success");
});
},
function(callback) {
col = db.collection(mycollection);
callback(null,"collection success");
},
function(callback) {
console.log ("insert begin ...");
for (var i = 1; i <= count; i++) {
console.log("inserting ....." + i);
col.insert({c:i}, function(error,result) {
if (error) {console.log("insert error:" + i);callback(error,"insert error"); return;}
});
}
callback(null,"insert success");
},
function (callback){
console.log ("close db");db.close();
callback(null,"connection closed");
}
], function(error, results) {
if (error) { console.log("error"); }
console.log(results);
});
輸出
insert begin ...
inserting .....1
inserting .....2
inserting .....3
inserting .....4
inserting .....5
close db
insert error:6
error
[ 'connect success', 'collection success', 'insert error' ]
insert error:6
insert error:6
insert error:6
insert error:6