【发布时间】: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