简体   繁体   中英

How can I update a property inside an object in Mongoose

i'm trying to update a property inside an object using $inc in mongoose. I've tried several ways but apparently the syntax is not valid.

this is the relevant part of the Schema:

stats: {
    type: {
      totalMatches: {
        type: Number,
        default: 0
      },
      totalWins: {
        type: Number,
        default: 0
      },
      totalRebuys: {
        type: Number,
        default: 0
      },
      totalTimesHosted: {
        type: Number,
        default: 0
      },
      averagePosition: {
        type: Number,
        default: 0
      },
      gainLossRatio: {
        type: Number,
        default: 0
      },
      totalFinishesForEachPosition: {
        type: [Number],
        default: [0]
      }
    }
  }
});

const UserModel = mongoose.model("User", userSchema);

This is the part for the update, the syntax error is inside the $inc block:

UserModel.savePokerResultToPlayerData = (game) => {
  _.each(game.results, (playerResult, index) => {
    let resultToSave = {
      matchId: game._id,
      date: game.date,
      ranking: index + 1,
      prizeMoney: playerResult.prizeMoney,
      rebuys: playerResult.rebuys,
      isHostPlayer: game.host === playerResult._id
    };
    const statsObject = prepareStatsDataToBeUpdated(resultToSave);
    UserModel.findByIdAndUpdate(
      playerResult._id,
      {
        $push: { results: resultToSave },
        $inc: {
          stats.totalMatches: 1,
          stats.totalWins: statsObject.totalWins,
          stats.totalRebuys: statsObject.totalRebuys,
          stats.totalTimesHosted: statsObject.totalTimesHosted
        }
      }
    )
    .exec()
    .then()
    .catch(err => {
      console.log('error: ' + err);
    });
  });
};

prepareStatsDataToBeUpdated = (resultToSave) => {
  return {
    totalWins: resultToSave.ranking === 1 ? 1 : 0,
    totalRebuys: resultToSave.rebuys,
    totalTimesHosted: resultToSave.isHostPlayer ? 1 : 0
  };
};

I've looked at a few similar questions here and tried the solution but all of them got me a syntax error. I know i can find the related user, work on it and save it but i believe it loses the purpose of $inc and $push.

Probably you got syntax error about javascript. It's forbidden to write invalid variable name on the left side of the ":" when you define object, here you use dot notation in place where have to be valid variable name or string:

stats.totalMatches: 1

please use quotes:

"stats.totalMatches": 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM