mongodb在nodejs中回调for循环

时间:2014-07-25 02:53:14

标签: node.js mongodb callback

我正在尝试使用Excel中的数据填充mongoDB集合。我想我理解回调的异步性质,因此在数据库回调之前使用另一个函数本地化了作用域。但是,我无法解决我的错误。

这是代码。

var http = require('http');
var parseXlsx = require('excel');
var mongo = require('mongoskin');
var faker = require('faker');
var moment = require('moment');
var ObjectID = require('mongodb').ObjectID;

var uristring =
    process.env.MONGOLAB_URI ||
    process.env.MONGOHQ_URL ||
    'mongodb://localhost:27017/loadmongo/data';


var db = mongo.db(uristring, {native_parser:true});

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
  console.log('connected');


});

http.createServer(function handler(req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

parseXlsx('userRegistration.xlsx', function(err, data) {
    if(err) throw err;


    console.log(data.length);
    console.log(data[0][0]);    

    for(var i = 0; i<= data.length; i++) {

        //(function(i){
        console.log('inside for loop');
        var t = Math.floor(Math.random()*10);
        var aCD = moment().subtract('days', t).format('MM DD YYYY');
        var tmpID = new ObjectID();
        console.log(data[i][0]);
        var tmp = {
                '_id': tmpID,
                'firstName': data[i][0],
                'lastName': data[i][1],
                'email1': data[i][2],
                'email2': data[i][3],
                'accountCreationDate': aCD,
                'location': {
                    'country' : data[i][9],
                    'city' : data[i][6],
                    'state' : data[i][7],
                    'stateCode' : data[i][7],
                    'zipcode' : data[i][10],
                    'streetName' : data[i][5],
                    'streetNumber' : data[i][4],
                    'countryCode' : data[i][8],
                    'longlat': {
                        'type' : "Point",
                        'coordinates': [data[i][12], data[i][11]]
                    }

                },
                'serviceNeededCurrent': {

                },
                'serviceOfferedCurrent': {

                },
                'serviceCompleted': {

                },
                'reviewsGiven': {

                },
                'reviewesRecieved': {

                },
                'financialRecords': {

                }
        };

        (function(tmp){
        db.collection('userRegistration').insert(tmp, function(err, result){
            if (err) {
                console.log(err);
                console.log('some error')

            }

            if (result)
                console.log('userRegistration Collection.. Done');


        }); 

        }(tmp));
    } //end of for loop


    }); // End of parsexlsx

这是输出

Server running at http://127.0.0.1:1337/
675
Ernesto

C:\workspace\workspace1\loadmongo\node_modules\excel\node_modules\node-promise\promise.js:204
          throw error;
                ^
TypeError: Cannot read property '0' of undefined
    at C:\workspace\workspace1\loadmongo\hello-world-server.js:43:22
    at C:\workspace\workspace1\loadmongo\node_modules\excel\excelParser.js:156:3
    at Object._onImmediate (C:\workspace\workspace1\loadmongo\node_modules\excel\node_modules\node-promise\promise.js:164:27)
    at processImmediate [as _immediateCallback] (timers.js:336:15)

1 个答案:

答案 0 :(得分:2)

哦对不起我没有意识到那些是你的console.log的输出!好的,你必须在data.length之前停止循环!

for (var i = 0; i < data.length; i++) {

数组索引范围从0<arrayLength>-1;)