Node.js MongoDB插入需要花费太多时间

时间:2018-05-25 07:49:13

标签: node.js mongodb

我有一个循环,我在MongoDB集合中插入文档。但是只插入最后一个文档,可能是,循环太快而无法插入。 如何让循环等待插入完成? 这是我的代码:

mongo.connect(url, function(err, db) {
        if (err) throw err;
        var dbo = db.db("mydb");
    for (var i = 0; i < totalEmployee; i++) {
            var some = array_data[index].split(":");
            var thing = some[1].split("\"");
            var EID = thing[1];
            var Info = [];
            index++;
            for (var j = 0; j < 2; j++) {
                var some = array_data[index].split(":");
                var thing = some[1].split("\"");
                var first = thing[1];
                thing = some[2].split("\"");
                var second = thing[0];
                Info[j] = first + ":" + second;
                index++;
            }
            console.log(Info);
            var unique = date + EID;
        dbo.collection("Attendance").find({_id: unique}).toArray(function (err, result) {
                if (!result.length) {
                    dbo.collection("Attendance").insertOne({
                            _id: unique,
                            Date: date,
                            EID: EID,
                            InTime: Info[0],
                            OutTime: Info[1]
                        },function(err, res) {
                            if (err) throw err;
                            console.log("1 document inserted");
                            inserted=false;
                        }
                    );

                }
                else {
                    console.log(unique+date+EID+Info[0]);
                    var myquery = {_id: unique};
                    var newvalues = {$set: {Date: date, EID: EID, InTime: Info[0], OutTime: Info[1]}};
                    dbo.collection("Attendance").updateOne(myquery, newvalues, function (err, res) {
                        if (err) throw err;
                        console.log("1 document updated");
                        inserted=false;
                    });
                }
    }
}

});

0 个答案:

没有答案