Javascript MongoDB。逐字段比较两个集合。脚本在嵌套数组上崩溃
我需要比较两个包含大量嵌套对象和数组的集合。这是一个文档的结构 这是我的密码Javascript MongoDB。逐字段比较两个集合。脚本在嵌套数组上崩溃,javascript,mongodb,Javascript,Mongodb,我需要比较两个包含大量嵌套对象和数组的集合。这是一个文档的结构 这是我的密码 function iterate_array (my_array, path, cur_id) { for(item in my_array) { if (item == "cloudTimestamp") { continue; } else if (typeof my_array[item] == "object")
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
您的代码中有错误:
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\u val['a.b.c']
,实际上应该类似于other\u val['a']['b']['c']
或other\u val.a.b.c.
。因此找不到键,因此从未定义中读取0。可能缺少数组索引,例如XrefHistory.0.myfieldName,其中0是数组索引?