我正在尝试创建一个类似于奖励制度的东西,我正在寻找实现这一目标的最佳选择。 根据增加的奖励,我必须将其价值增加一。 这是我的模型的样子:
const CardSchema = new mongoose.Schema({
awards: {
"awardOne": 0,
"awardTwo": 0,
"awardThree": 0,
"awardFour": 0
},
userId: {
type: mongoose.Schema.ObjectId,
ref: 'User',
required: true
},
})
现在最好是增加一个最佳方法,例如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
})
});
答案 0 :(得分:0)
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
})
});