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:
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.
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
})
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.