[英]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.我正在尝试在 mongoose 中使用 $inc 更新对象内的属性。 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:这是更新的部分,语法错误在 $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
};
};
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.
我知道我可以找到相关用户,对其进行处理并保存它,但我相信它失去了 $inc 和 $push 的目的。
Probably you got syntax error about javascript.可能您遇到了有关 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.