[英]How to increment the value of an object in an array of objects. Mongoose and MongoDB
I'm trying to create something like an award system and I'm looking for the best option to do that.我正在尝试创建类似奖励系统的东西,我正在寻找最好的选择来做到这一点。 Depending on which award was incremented I have to increase by one the value of it.
根据增加的奖励,我必须将其价值增加一。 This is what my model looks like:
这就是我的 model 的样子:
const CardSchema = new mongoose.Schema({
awards: {
"awardOne": 0,
"awardTwo": 0,
"awardThree": 0,
"awardFour": 0
},
userId: {
type: mongoose.Schema.ObjectId,
ref: 'User',
required: true
},
})
Now what is the best way of incrementing by one for example awardOne.现在增加一的最佳方法是什么,例如awardOne。
exports.awardCard = asyncHandler(async (req, res, next) => {
const id = req.params.id;
const awardOption = req.body.award; //Name of the award
const card = Card.findById(id)
if(!card){
res.status(200).json({
success: false,
message: "Card not found"
}
card.update ... //This is where I don't know how to manage the update
card.save()
res.status(200).json({
success: true,
card
})
});
exports.awardCard = asyncHandler(async (req, res, next) => {
const id = req.params.id;
const awardOption = req.body.award; //Name of the award
const card = await Card.findOneAndUpdate({"_id":id}, { $inc: { [`awards.${awardOption}`]: 1 } }, {new: true});
if(!card){
res.status(200).json({
success: false,
message: "Card not found"
}
res.status(200).json({
success: true,
card
})
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.