[英]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.