首页 > 解决方案 > 更改对象数组中对象中的字段

问题描述

我有一个achivment包含对象数组的字段。我需要更新currenPoints一个对象中的字段,我将通过name数组中的字段找到该对象。
mongoose的代码模型:

const achive = new Schema(
   {
      achiveId: ObjectId,
      name: { type: String, required: true },
      finishedPoints: { type: Number, required: true },
      currentPoints: {
         type: Number,
         default: 0,
         set: function (v) {
            if (v >= this.finishedPoints) this.isFinished = true;
            return v;
         }
      },
      isFinished: { type: Boolean, default: false }
   },
   { _id: false }
);

const achivesSchema = new Schema({
   userId: ObjectId,
   achivement: [achive]
});

代码查询:

export async function progressAchive(req, res) {
   const value = 3;
   try {
      const test = await Achives.updateOne(
         {
            userId: req.user._id,
            achivement: { $elemMatch: { name: req.params.nameAchive } }
         },
         { $set: { achivement: { currentPoints: value } } },

         { new: true }
      );
      res.json(test);
   } catch (e) {
      console.log(e);
   }
}

它不是更新,而是从数组中删除所有对象,并将它们保留为一个包含该currentPoint字段的对象。我怎样才能像我想要的那样更新它?

标签: mongodbexpressmongoose

解决方案


您应该使用以下内容进行更新

    const test = await Achives.updateOne(
      {
        userId: req.user._id, 
      },
    {
      $set:{"achivement.$[el].currentPoints": value}
    }, 
    { 
      arrayFilters:[{
        "el.name": req.params.nameAchive
      }],
      new: true
    }
  );

推荐阅读