【问题标题】:How can I update a property inside an object in Mongoose如何在 Mongoose 中更新对象内的属性
【发布时间】:2020-04-20 11:30:24
【问题描述】:

我正在尝试使用 mongoose 中的 $inc 更新对象内部的属性。我尝试了几种方法,但显然语法无效。

这是 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);

这是更新的部分,语法错误在 $inc 块内:

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
  };
};

我在这里查看了一些类似的问题并尝试了解决方案,但所有这些问题都让我遇到了语法错误。 我知道我可以找到相关用户,对其进行处理并保存它,但我认为它失去了 $inc 和 $push 的目的。

【问题讨论】:

  • 不应该是stats.type.totalMatches而不是stats.totalMatches吗?
  • 否,因为类型字定义了属性的类型。在这种情况下,stats 是对象类型。

标签: javascript node.js mongodb mongoose nosql


【解决方案1】:

您可能遇到了有关 javascript 的语法错误。 定义对象时,禁止在“:”左侧写入无效的变量名,此处使用点表示法,必须是有效的变量名或字符串:

stats.totalMatches: 1

请使用引号:

"stats.totalMatches": 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-21
    • 2021-10-20
    • 1970-01-01
    • 2022-01-07
    • 2016-08-08
    • 1970-01-01
    相关资源
    最近更新 更多