简体   繁体   English

如何在对象数组中增加 object 的值。 ZCCADDEDB567ABAE643E15DCF0974E503Z 和 MongoDB

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

相关问题 (MongoDB / Mongoose)增加对象数组中的值 - (MongoDB / Mongoose) Increment a value in an array of objects 猫鼬-在对象数组内增加一个值 - Mongoose - Increment a value inside an array of objects 如何增加 object、MongoDB 中的值 - How to increment value in an object, MongoDB Mongoose 检索对象数组。 对于每个对象,我只想要两个属性 - Mongoose retrieve array of objects. For each object, I only want two properties 如何使用nodejs在MongoDB中增加数组object中的值? - How to increment a value inside an array object in MongoDB using nodejs? 如何在 mongoose 模式的对象数组中更改特定 object 的值? - how to change a value of specific object in an array of objects in mongoose schema? 如何使用 mongoose 在 mongodb 中保存对象数组? - How to save array of objects in mongodb with mongoose? 无法从对象数组中过滤出具有特定值的特定 object。 反应(待办事项应用程序) - Unable to filter out a specific object with a specific value from an array of objects. React ( todo app ) 我有一个对象数组。 每个 object 都包含最大和最小键值对。 如何找到包含预定义值的 object? - I have an array of objects. Each object contains max and min key value pairs. How do I find the object that contains a predefined value? 如何更新数组中的嵌套 object (Mongoose/MongoDB) - How to update nested object in array (Mongoose/MongoDB)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM