Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a new property to Mongoose Document after fetch [duplicate]

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?

like image 991
Emilia Tyl Avatar asked Jul 21 '15 08:07

Emilia Tyl


1 Answers

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.

like image 178
TaoPR Avatar answered Nov 15 '22 20:11

TaoPR