I'm setting up an API for my server and I'm trying to update a value in a JSON consisted of country codes and numerical values. I loop through an array of JSON retrieved from my DB (MongoDB) and update the value, then after the loop is finished I'm trying to return the updated list.
The problem is that the return value is the original list, without the updates. I've verified that the update is happening inside the loop.
I'm quite new to JS, so I've tried switching between let
and const
, tried updating countryList
directly (but as I read through some posts, I understood that js passes all arguments by value, and not by reference).
//shortened list, just for the example. The original has all country codes.
const countryList = JSON.parse('{"ZW": 0, "ZM": 0, "ZA": 0, "YT": 0, "YE": 0, "WS": 0, "WF": 0}');
let updateCountryList = () => {
let temp = countryList;
db.collection('tweets').find({'place': {$ne: null}}).forEach((item) =>{
if (item.emoji_list.includes(emoji)) {
temp[item["place"]["country_code"]] += 1;
console.log(temp); //prints updated list
}
});
console.log(temp); //prints original, empty list
return temp
};
The expected output, given the JSON above, should look like:
{"ZW": 5, "ZM": 896, "ZA": 466, "YT": 23, "YE": 0, "WS": 1, "WF": 0}
I should mention that this is a part of a promise and a longer process. However, this is the first thing that happens.
Edit: This is what solved it:
const countryList = JSON.parse('{"ZW": 0, "ZM": 0, "ZA": 0, "YT": 0);
let updateCountryList = () => {
return new Promise(resolve1 => {
let temp = countryList;
db.collection('tweets').find({'place': {$ne: null}}).forEach((item) => {
if (item.emoji_list.includes(emoji)) {
temp[item["place"]["country_code"]] += 1;
}
}).then(() => {
resolve1(temp)
});
});
};
updateCountryList().then(temp => {
console.log(temp); // WORKS :)
});