我有一个简单的更新脚本,由于某种原因,它会遍历每个文档两次并继续执行代码。我不明白为什么会这样......任何帮助将不胜感激:
db.products.find().forEach(function(product) {
var numerator = {
0 : [],
1 : [],
2 : [],
3 : [],
4 : []
},
denominator= {
0 : [],
1 : [],
2 : [],
3 : [],
4 : []
};
product.reviews.forEach(function(review) {
var weight = review.weight.reputation + review.weight.reviewRelevance,
i = 0;
review.score.forEach(function(score) {
if ( i == 0){
score.rating = Math.ceil((score.rating/100) * 10);
}else {
score.rating = Math.ceil((score.rating/25) * 10);
numerator[i].push(score.rating * weight);
denominator[i].push(weight);
i++;
}
});
var s = 0;
for (var key in product.score) {
var obj = product.score[key];
if ( key == 'Overall'){
obj.percent = obj.rating;
obj.rating = Math.ceil((obj.rating/100) * 10);
}else {
obj.rating = Math.ceil((obj.rating/25) * 10);
}
obj.info = {
'numerator' : array_sum(numerator[s]),
'denominator' : array_sum(denominator[s]),
};
s++;
}
});
db.products.save(product);
});
function array_sum (array) {
var key, sum = 0;
if (array && typeof array === 'object' && array.change_key_case) { // Duck-type check for our own array()-created PHPJS_Array
return array.sum.apply(array, Array.prototype.slice.call(arguments, 0));
}
// input sanitation
if (typeof array !== 'object') {
return null;
}
for (key in array) {
if (!isNaN(parseFloat(array[key]))) {
sum += parseFloat(array[key]);
}
}
return sum;
}