![](/img/trans.png)
[英]How can I remove a property of object from an array in Mongoose? !Important
[英]How can I update a property inside an object in Mongoose
我正在尝试在 mongoose 中使用 $inc 更新对象内的属性。 我尝试了几种方法,但显然语法无效。
这是架构的相关部分:
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 的目的。
可能您遇到了有关 javascript 的语法错误。 定义对象时,禁止在“:”的左边写无效的变量名,这里在必须是有效的变量名或字符串的地方使用点表示法:
stats.totalMatches: 1
请使用引号:
"stats.totalMatches": 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.