I have a problem with understanding the variable manipulation in JavaScript. Following code:
UserScore.find(filter, function (err, userScores) {
var contests = [];
userScores.forEach(function(userScore)
{
contests.push(userScore.ContestId);
});
Contest.find({ '_id': { $in : contests } }, function(err, contestItems)
{
var result = [];
contestItems.forEach(function(con)
{
userScores.forEach(function(element) {
if(element.ContestId == con._id)
{
con.UserTeamName = element.TeamName;
con.UserPersonalScore = element.Score;
console.log(con);
console.log(con.UserPersonalScore);
result.push(con);
return;
}
});
});
res.status(200).json(result);
});
});
prints "con" without the two added properties, and prints "con.UserPersonalScore" with the appropriate value. When pushed to result, con does not have additional properties. What am I missing?
I guess I am somehow creating local variables instead of properties, but why isn't it being pushed to the result array?
Object returned from Mongodb query is in frozen (immutable) state
Your code seems to interact with MongoDB. The object returned is actually a Mongodb model instance, not a plain javascript object. You can't modify the object returned from a query.
To convert the Mongodb document to a JSON object
.toObject()
does the trick. It converts a frozen MongoDB document to a JSON object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With