2016-01-19 30 views
0

我需要比较两个集合与很多嵌套的对象和数组。这里是 structure of a single documentMongoDB。逐个比较两个集合。脚本崩溃嵌套数组

文档的结构,这里是我的代码

function iterate_array (my_array, path, cur_id) { 
    for(item in my_array) { 
      if (item == "cloudTimestamp") { 
        continue; 
      } else if (typeof my_array[item] == "object") { 
        var x = path.slice(); 
        x.push(item); 
        iterate_array(my_array[item], x, cur_id); 
      } else if (typeof my_array[item] == "function") { 
        continue; 
      } else { 
        other_val = otherdb.product.findOne({"_id" : cur_id}); 
        if (path == '') { 
          if (my_array[item] == other_val[item]) { 
            print("field matched"); 
          } else { 
            print("field NOT matched"); 
          } 
        } else { 
          var string_path = JSON.stringify(path).replace(/[^A-Za-z0-9,]/g, '').replace(/,/g, '.'); 
          if (my_array[item] == other_val[string_path][item]) { 
            print("field matched"); 
          } else { 
            print("field NOT matched"); 
          } 
        } 
      } 
    } 
} 

var db = db.getSiblingDB('smcdb_bos_new'); 
var otherdb = db.getSiblingDB('smcdb_boa_new'); 
var cursor = db.product.find(); 
cursor.forEach(function (mydoc) { 
    iterate_array(mydoc, [], mydoc['_id']); 
}); 

脚本工作,直到达到XrefHistory.values阵列。然后,它崩溃,出现以下错误:

2016-01-19T07:15:38.566-0500 TypeError: Cannot read property '0' of undefined at compare.js:22 
+0

也许你缺少数组索引,例如XrefHistory.0.myfieldName,其中0是数组索引? – savtand1

回答

0

也有一些是错误的代码:

var string_path = JSON.stringify(path).replace(/[^A-Za-z0-9,]/g, '').replace(/,/g, '.'); 
if (my_array[item] == other_val[string_path][item]){ 
... 
} else 
{ 
} 

尝试由other_val,这是行不通的与string_path访问数据。你试图做的是other_val['a.b.c'],实际上应该是other_val['a']['b']['c']other_val.a.b.c.。所以没有找到密钥,因此从undefined读取0。